wikis / Redis / wiki / concepts / sets-and-sorted-sets.md view as markdown report a mistake
Redis Sets and Sorted Sets
Sets
A Redis set is an unordered collection of unique strings (members). Sets efficiently track unique items, represent relations, and perform set operations. Adding, removing, and membership tests are O(1).
SADD key member...— add members (creates the key); duplicates are silently ignored.SREM,SCARD(count, O(1)),SISMEMBER/SMISMEMBER(membership, O(1)),SMEMBERS(all members, O(N)),SSCAN(iterative),SPOP,SRANDMEMBER,SMOVE.- Combinations:
SINTER,SUNION,SDIFF(andSINTERCARDplus the...STOREvariants that save results to a key).
> SADD bikes:racing:france bike:1 bike:2 bike:3
(integer) 3
> SADD bikes:racing:usa bike:1 bike:4
(integer) 2
> SINTER bikes:racing:france bikes:racing:usa
1) "bike:1"
> SDIFF bikes:racing:france bikes:racing:usa
1) "bike:3"
2) "bike:2"
Max set size is 2^32 - 1 (4,294,967,295) members. SMEMBERS is O(n) and returns the whole set — prefer SSCAN for large sets. For approximate membership with low memory, consider a Bloom or Cuckoo filter (see probabilistic and geospatial).
Sorted sets
A sorted set is a collection of unique strings (members) ordered by an associated floating-point score; members with equal scores are ordered lexicographically. Use cases include leaderboards and sliding-window rate limiters.
ZADD key score member [score member ...]— add members or update scores (creates the key); O(log(N)) per item.ZSCORE/ZMSCORE,ZINCRBY,ZCARD,ZRANK/ZREVRANK,ZCOUNT,ZREM.
> ZADD racer_scores 10 "Norem"
(integer) 1
> ZADD racer_scores 8 "Sam-Bodden" 10 "Royce" 6 "Ford" 14 "Prickett"
(integer) 4
Operating on ranges
ZRANGE key start stop— members by index range (withBYSCORE,BYLEX,REV,LIMIToptions); O(log(N)+M).ZRANGEBYSCORE key min max— members within a score range (-inf/+infsupported).ZRANGEBYLEX/ZLEXCOUNT— lexicographical range queries.ZREVRANGE,ZRANGEBYSCORE,ZPOPMIN/ZPOPMAX(and blockingBZPOPMIN/BZPOPMAX/BZMPOP),ZREMRANGEBY*.
> ZRANGEBYSCORE racer_scores -inf 10
1) "Ford"
2) "Sam-Bodden"
3) "Norem"
4) "Royce"
Most sorted set operations are O(log(n)); ZRANGE is O(log(n)+m) — use caution with large return values.
Related: data types overview, probabilistic and geospatial, json, redis cli.
