如何使用Redis排序列表

排序的集合将等级与集合中的每个项目相关联。

排序的集合的工作方式与集合类似,并且它们使用类似的命令,除了S就是现在Z, 例如:

  • SADD->ZADD
  • SPOP->ZPOP

但是它们略有不同。

ZADD接受一个分数

ZADD names 1 "Flavio"
ZADD names 2 "Syd"
ZADD names 2 "Roger"

As you can see, values must still be unique, but now they are associated to a score.

The score does not have to be unique.

Items in a set are always sorted by the score.

This is very useful to implement some kind of data storage tool like (usual example) a leaderboard. Or to indicate the time some item was added, with a timestamp.

You can get the score of an item using ZRANK:

ZRANK names "Flavio"

List all items in a sorted set using ZRANGE, which works similarly to LRANGE in lists:

ZRANGE names 0 -1

Add WITHSCORES to also return the scores information:

You can increment the score of an item in the set using ZINCRBY.

See all the sorted sets commands here.


More redis tutorials: