What is Sorted Set in Redis: Explanation and Examples
sorted set in Redis is a collection of unique elements where each element is associated with a score, and the elements are stored in order based on these scores. It allows fast access to elements by their rank or score, making it useful for ranking and leaderboard systems.How It Works
Think of a sorted set in Redis like a leaderboard in a game. Each player (element) has a score, and the leaderboard keeps players sorted from highest to lowest score. Redis stores these elements uniquely, so no duplicates exist, and it keeps them ordered automatically by their score.
When you add or update an element's score, Redis places it in the right position so you can quickly find the top players or those within a certain score range. This is efficient because Redis uses a special data structure combining a hash and a skip list behind the scenes.
Example
This example shows how to add elements with scores to a sorted set and retrieve them in order.
ZADD leaderboard 100 "Alice" ZADD leaderboard 200 "Bob" ZADD leaderboard 150 "Charlie" ZRANGE leaderboard 0 -1 WITHSCORES
When to Use
Use sorted sets when you need to keep items in order by a numeric value and retrieve them quickly. Common use cases include:
- Leaderboards in games or competitions
- Ranking items by popularity or score
- Scheduling tasks by priority or time
- Implementing time-series data with scores as timestamps
Sorted sets are perfect when you want to query ranges by rank or score efficiently.
Key Points
- Sorted sets store unique elements with a numeric score.
- Elements are automatically ordered by score.
- Supports fast range queries by rank or score.
- Useful for leaderboards, rankings, and priority queues.