Redis Sorted Sets (ZSet) are an extension of regular sets, where each unique item has an associated score. This allows the set to be automatically ordered by score, making it extremely useful for ranking, leaderboards, and priority queues.
Key Features of ZSet
- Unique Items: Like regular sets, duplicate members are not allowed.
- Scores: Each member has a numeric score used for ordering.
- Automatic Sorting: Members are ordered based on their score. If scores are equal, members are ordered lexicographically (dictionary order).
- Ranks: The rank of a member is its position in the ordered set, starting from 0 for the lowest score.
- Priority Queue: ZSet can be used to implement priority queues where higher scored items are processed first.
Common Use Cases
- Tracking most frequently ordered products.
- Finding top-rated movies or products.
- Leaderboards or ranking systems.
- Frequently visited pages or high-priority tasks.
Basic Commands
1. Adding Items (ZADD)
ZADD products 0 book 0 tv 0 iphone
products→ key name for the sorted set.score→ numeric value for sorting.member→ item to store.- Multiple items can be added at once with their respective scores.
- If the member already exists, its score is updated.
2. Checking Set Size (ZCARD)
ZCARD products
- Returns the number of items in the sorted set.
3. Incrementing Scores (ZINCRBY)
ZINCRBY products 1 book
- Increases the score of
bookby 1. - Useful for tracking quantities like order counts, visits, or votes.
4. Retrieving Members in Order (ZRANGE)
ZRANGE products 0 -1
- Returns all members in ascending order by score.
- Use the
WITHSCORESoption to see scores as well:
ZRANGE products 0 -1 WITHSCORES
- Example output:
book:1, tv:1, iphone:2 - Items with equal scores are sorted lexicographically.
5. Retrieving Members in Reverse Order (ZREVRANGE)
ZREVRANGE products 0 -1 WITHSCORES
- Returns members in descending order by score.
- Useful for top-ranked items.
6. Getting Rank of a Member (ZRANK / ZREVRANK)
ZRANK products book
- Returns the rank (position) of
bookin ascending order. ZREVRANKreturns the rank in descending order.
7. Getting Score of a Member (ZSCORE)
ZSCORE products iphone
- Returns the score associated with the member.
8. Removing Members (ZREM)
ZREM products iphone
- Removes the specified member from the sorted set.
9. Popping Members (ZPOPMAX / ZPOPMIN)
ZPOPMAX products→ removes and returns the member with the highest score.ZPOPMIN products→ removes and returns the member with the lowest score.- This allows implementing priority queue-like behavior, where high-score items are processed first.
Example Workflow
- Add products with initial scores:
ZADD products 1 book 1 tv 2 iphone
- Increment scores as orders arrive:
ZINCRBY products 1 book ZINCRBY products 1 iphone
- Get all products ordered by score:
ZRANGE products 0 -1 WITHSCORES # Output: book:2, tv:1, iphone:3
- Find top product:
ZREVRANGE products 0 0 WITHSCORES # Output: iphone:3
- Pop the highest-priority product:
ZPOPMAX products # Output: iphone:3
- Check rank of a product:
ZRANK products book ZREVRANK products tv
Important Notes
- Members must be unique, but scores can be repeated.
- If multiple members have the same score, lexicographical order decides the ranking.
- Using decimal scores can help break ties if needed.
- Sorted sets are ideal for leaderboards, top lists, and priority queues.
Using Redis Sorted Sets (ZSet) as a Priority Queue
Redis Sorted Sets (ZSet) can be effectively used to implement a priority queue, where items with higher or lower scores are processed first depending on your business logic. This is especially useful in scenarios like order processing, task scheduling, or job queues.
Concept
- Each item in a sorted set has a score representing its priority.
- Lower scores can represent higher priority, or vice versa, depending on your design.
- Redis automatically keeps the set ordered by score, so retrieving items in order of priority is straightforward.
- Commands like
ZPOPMAXandZPOPMINallow you to pop items based on their priority, effectively implementing a queue.
Example: Auto Service Order Processing
Imagine an auto service application where orders are placed by users. Some users are prime members, and some are non-prime. You want to process prime orders first.
- Assigning Scores:
- Prime users → lower score (higher priority) →
0 - Non-prime users → higher score (lower priority) →
99
- Adding Orders to the Sorted Set:
ZADD orders 0 order:prime:001 ZADD orders 99 order:nonprime:001
orders→ key name for the ZSet.0and99→ scores representing priority.- Members represent order IDs or details.
- Processing Orders in Priority:
- The shipping service retrieves items based on ascending order of score (prime first):
ZPOPMIN orders
ZPOPMINremoves and returns the item with the lowest score.- Example output:
order:prime:001
- After this, the next item processed will be:
order:nonprime:001
Key Notes
- Prime users are processed first because their score is lower.
- Non-prime users will be processed afterward due to higher scores.
- This approach ensures priority-based processing without additional sorting logic.
- Scores can be dynamic. For example, if a non-prime user becomes a prime user, you can update their score with:
ZINCRBY orders -99 order:nonprime:001
- Redis automatically reorders the set based on the updated score.
Benefits of Using ZSet as Priority Queue
- Efficient and automatic sorting by priority.
- Supports dynamic score updates.
- Built-in commands (
ZPOPMIN,ZPOPMAX) make queue operations simple. - Can handle large datasets with minimal overhead.
