首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Redis ZSET

Redis ZSET

作者头像
九州暮云
发布2019-08-21 10:20:34
4140
发布2019-08-21 10:20:34
举报
文章被收录于专栏:九州牧云九州牧云九州牧云

For the past 2 years I’ve been all about Redis, and something I’m continually excited about is ZSET.

It is a sorted set implementation built into Redis. Its super fast, flexible, and I use it all the time, probably sometimes just because its fun.

I’ll show how it works, and outline two situations I’ve found it to be especially effective.

How is it used?

The simplest operation is to set a value for a given key. Imagine we want to record ages in a sorted set:

redis 127.0.0.1:6379> ZADD "ages" 25 "john"
(integer) 1
redis 127.0.0.1:6379> ZADD "ages" 30 "joe"
(integer) 1

Once they’re in, we can query them in order. To get the entries out, ordered by their rank:

redis 127.0.0.1:6379> ZRANGE 'ages' 0 1
1) "john"
2) "joe"

It may be useful to see them in the reverse order (highest to lowest):

It may be useful to see them in the reverse order (highest to lowest):

Or to have their scores returned alongisde them:

redis 127.0.0.1:6379> ZREVRANGE 'ages' 0 1 WITHSCORES
1) "joe"
2) "30"
3) "john"
4) "25"

You can also do these ranges by score (ZRANGEBYSCORE), increment members (ZINCRBY), remove ranges (ZREMRANGEBYSCORE, ZREMRANGEBYRANK), or just query for scores (ZSCORE).

The cool part about this, is that these operations are so simple, that you can use them as persisted copies of data structures, that can exist between multiple services, or multiple hosts/nodes. In fact, that’s exactly what projects like redis-objects exist to make easy.

Use: Scoring things

This is probably the first thing most people think of with the sorted set. When something happens, we can bump up the value of a given key by a certain value and then query for the top values (or lowest values) easily using ZINCRBY, and efficiently.

Use: Queryable Dated Entries

Another use I come into pretty often is to make the values UNIX timestamps, and put data in the keys. With the set you can easily query for date ranges, get get the oldest and most recent entries, and easily purge ranges of results when they re no longer relevant (by date using ZREMRANGEBYSCORE, or by limit with ZREMRANGEBYRANK.

And then..

What’s your favorite use of ZSET?

Note on Documentation

One thing that’s really neat about the redis documentation is that they describe the runtime of each method right at the top. Check out the ZSET documentation for more details!

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • How is it used?
  • Use: Scoring things
  • Use: Queryable Dated Entries
  • And then..
  • Note on Documentation
相关产品与服务
云数据库 Redis
腾讯云数据库 Redis(TencentDB for Redis)是腾讯云打造的兼容 Redis 协议的缓存和存储服务。丰富的数据结构能帮助您完成不同类型的业务场景开发。支持主从热备,提供自动容灾切换、数据备份、故障迁移、实例监控、在线扩容、数据回档等全套的数据库服务。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档