Sets and sorted sets
A set is an unordered collection of unique strings. A sorted set adds a score to each member and keeps members ordered by it. Sorted sets are one of Redis's superpowers: leaderboards, rankings, priority queues and time-based indexes all become a few commands.
Sets
redis was added twice but stored once: SADD returns how many new members were added. Checking membership with SISMEMBER is instant, however big the set.
Unique visitors
Each user is counted once per day, however many times they visit. (For hundreds of millions of visitors, Redis's HyperLogLog type counts uniques approximately using only 12 KB.)
Set operations
The real power: combine sets on the server.
| Command | Gives |
|---|---|
SINTER |
Members in all sets: friends in common |
SUNION |
Members in any set |
SDIFF |
Members of the first set not in the others: "people Asha follows that Rahul doesn't" |
…STORE variants |
Save the result in a new key |
Random members
SRANDMEMBER peeks at random members; SPOP removes and returns one, which is ideal for picking a winner. (Your results will differ each run: they're random!)
Sorted sets
Each member of a sorted set has a numeric score, and the set is always ordered by score (then alphabetically for ties).
A game leaderboard
ZRANGElists low to high;ZREVRANGEhigh to low (orZRANGE … REV).ZREVRANKgives a member's position from the top, starting at 0 (so1means 2nd place).ZINCRBYadds points atomically, and the ordering updates instantly.
Every operation takes logarithmic time, so a leaderboard with 10 million players is just as fast. That's why so many games use Redis.
Ranges by score
( makes a bound exclusive; -inf and +inf mean no limit.
Timestamps as scores: recent activity and expiring members
Use a Unix timestamp as the score, and the sorted set becomes a time index:
A priority queue
The lowest score comes out first:
Choosing a type
| Need | Use |
|---|---|
| Ordered items, add/remove at the ends | List |
| Unique items, membership checks, intersections | Set |
| Unique items ranked or ordered by a number | Sorted set |
| Fields of one object | Hash |
Practice
- Create sets of skills for two developers and find skills they share and skills only the first one has.
- Build a leaderboard of 5 players, give one player 300 bonus points, and show the top 3 with scores.
- Find which rank (1-based!) a player is at. (Hint:
ZREVRANK+ 1.)
1.What does SADD s a b a return when s didn't exist?
2.Which command shows the top 10 players with their scores?
3.Which type fits "users who liked this post" (and checking whether one user liked it)?