Sets and Sorted Sets
Membership, and the structure nothing else has.
A set holds unique members with no order. Add a number to each member and you get a sorted set — the structure no other database gives you this cheaply.
Sets
SADD ignores duplicates, and the reply counts what was actually new:
SADD tags redis cache redis
SCARD tags
SISMEMBER tags redis
SISMEMBER tags nopeThree arguments, two members — uniqueness is the type’s job. SREM removes, counting what
it found:
SADD s a b c
SREM s a z
SMEMBERS sSet algebra
Three set operations, computed on the server:
SADD admins ada linus
SADD active ada grace
SINTER admins active
SDIFF admins activeSINTER is who is in both, SDIFF who is only in the first, SUNION everyone.
SINTERCARD counts without building the result, and SINTERSTORE keeps it:
SADD a x y z
SADD b y z w
SINTERCARD 2 a b
SINTERSTORE both a b
SMEMBERS bothRandom members
SRANDMEMBER peeks, SPOP removes — both useful for sampling:
redis-cli SADD deck a b c
redis-cli SPOP deck
redis-cli SPOP deck
redis-cli SCARD deckScores
ZADD attaches a number to each member, and the set stays sorted by it:
ZADD z 2 b 1 a 3 c
ZRANGE z 0 -1Adding an existing member updates its score instead of duplicating it:
ZADD z 1 a
ZADD z 5 a
ZSCORE z a
ZCARD zGT only raises a score, which is what a high-score table needs:
ZADD best 5 ada
ZADD best GT 9 ada
ZSCORE best ada
ZADD best GT 2 ada
ZSCORE best adaReading by rank
WITHSCORES interleaves scores with members, and REV reverses:
ZADD z 1 a 2 b 3 c
ZRANGE z 0 -1 WITHSCORES
ZRANGE z 0 -1 REVLT is the mirror of GT, and NX/XX work as in chapter 2’s SET. ZRANK gives a
member’s position, ZSCORE its number:
ZADD z 10 ada 20 linus
ZRANK z ada
ZREVRANK z ada
ZSCORE z nope
ZRANK z nopeReading by score
This is the range query Redis does have:
ZADD z 10 a 20 b 30 c
ZRANGEBYSCORE z 15 25
ZRANGEBYSCORE z (10 30
ZCOUNT z 10 20Moving a member
ZINCRBY changes a score in place, and the order follows:
ZADD scores 10 ada 20 linus
ZINCRBY scores 15 ada
ZRANGE scores 0 -1 WITHSCORESA leaderboard
Top three, highest first, with scores:
ZADD lb 50 ada 90 grace 70 linus 30 bob
ZRANGE lb 0 2 REV WITHSCORES
ZREVRANK lb graceA time index
Use a timestamp as the score and the sorted set becomes a time-ordered log you can trim:
ZADD events 1000 e1 2000 e2 3000 e3
ZRANGEBYSCORE events 1500 +inf
ZREMRANGEBYSCORE events -inf 1500
ZRANGE events 0 -1A ( makes a bound exclusive, and ZREMRANGEBYSCORE gives bounded retention with no
cleanup job.
Rate limiting
The same two commands become a sliding window — drop what is outside it, then count:
ZADD hits 100 r1 200 r2 300 r3
ZREMRANGEBYSCORE hits -inf 150
ZCARD hits
ZADD hits 400 r4
ZCARD hits