Working with Sorted Sets
1. Adding Sorted Set Members
| Command | Flags |
|---|---|
ZADD key [NX|XX] [GT|LT] [CH] [INCR] score m [score m ...] | NX add only, XX update only, GT/LT compare, CH return changed count, INCR like ZINCRBY |
Example: Leaderboard update
ZADD leaderboard 1500 alice 1200 bob
ZADD leaderboard GT 1800 alice # only update if 1800 > current
2. Removing Members
| Command | Description |
|---|---|
ZREM key m [m ...] | Remove specific members |
ZREMRANGEBYRANK key start stop | Remove by index |
ZREMRANGEBYSCORE key min max | Remove by score |
ZREMRANGEBYLEX key min max | Remove by lex range |
3. Getting Members by Rank
| Command | Notes |
|---|---|
ZRANGE key start stop [REV] [WITHSCORES] | Unified range command 6.2+ |
ZRANGE key min max BYSCORE [LIMIT off cnt] | Score-based |
ZRANGE key min max BYLEX | Lex range (equal scores) |
ZRANGESTORE dst src ... | Store range to another zset |
4. Getting Members by Score
ZRANGEBYSCORE prices 10 50 WITHSCORES LIMIT 0 100
ZRANGE prices (10 50 BYSCORE # exclusive 10, inclusive 50
ZRANGE prices -inf +inf BYSCORE # all
| Notation | Meaning |
|---|---|
(value | Exclusive |
-inf / +inf | Unbounded |
5. Getting Member Score
| Command | Returns |
|---|---|
ZSCORE key member | Score or nil |
ZMSCORE key m1 m2 ... | Array of scores 6.2+ |
6. Getting Member Rank
| Command | Direction |
|---|---|
ZRANK key member [WITHSCORE] | 0-based ascending 7.2+ |
ZREVRANK key member [WITHSCORE] | 0-based descending |
7. Getting Set Cardinality
| Command | Returns |
|---|---|
ZCARD key | Total member count |
8. Counting by Score Range
| Command | Description |
|---|---|
ZCOUNT key min max | Count in score range |
ZLEXCOUNT key min max | Count in lex range |
9. Incrementing Member Score
| Command | Returns |
|---|---|
ZINCRBY key amount member | New score as string |
10. Removing by Rank
ZREMRANGEBYRANK leaderboard 0 -101 # keep top 100
| Command | Returns |
|---|---|
ZREMRANGEBYRANK key start stop | Removed count |
11. Removing by Score
| Command | Returns |
|---|---|
ZREMRANGEBYSCORE key min max | Removed count |
12. Popping Min and Max Members
| Command | Description |
|---|---|
ZPOPMIN key [count] | Lowest scored |
ZPOPMAX key [count] | Highest scored |
BZPOPMIN k1 k2 ... timeout | Blocking variant |
ZMPOP numkeys k1 ... MIN|MAX [COUNT n] | Pop from first non-empty 7.0+ |
13. Computing Sorted Set Union
| Command | Aggregation |
|---|---|
ZUNION numkeys k1 ... [WEIGHTS] [AGGREGATE SUM|MIN|MAX] [WITHSCORES] | Returns members |
ZUNIONSTORE dst numkeys k1 ... | Stores result |
14. Computing Sorted Set Intersection
| Command | Description |
|---|---|
ZINTER numkeys k1 ... | Intersection |
ZINTERSTORE dst numkeys k1 ... | Store result |
ZINTERCARD numkeys k1 ... [LIMIT n] | Cardinality only 7.0+ |
ZDIFF numkeys k1 k2 ... | Difference |
ZDIFFSTORE dst numkeys k1 ... | Store difference |
15. Scanning Sorted Set
| Command | Returns |
|---|---|
ZSCAN key cursor [MATCH p] [COUNT n] | Member/score pairs |