0
0
Redisquery~5 mins

ZRANGE and ZREVRANGE for reading in Redis

Choose your learning style9 modes available
Introduction
ZRANGE and ZREVRANGE help you get items from a sorted list in order or reverse order. This is useful when you want to see top scores or recent items.
You want to see the top 5 players in a game leaderboard.
You want to get the latest 10 messages sorted by time.
You want to list products sorted by price from low to high or high to low.
You want to read a range of dates from a timeline in order.
You want to fetch items ranked by popularity in reverse order.
Syntax
Redis
ZRANGE key start stop [WITHSCORES]
ZREVRANGE key start stop [WITHSCORES]
start and stop are zero-based indexes; 0 is the first item.
WITHSCORES option returns the scores along with the items.
Examples
Get the first 5 items from the sorted set 'leaderboard' in ascending order.
Redis
ZRANGE leaderboard 0 4
Get the top 3 items from 'leaderboard' in descending order with their scores.
Redis
ZREVRANGE leaderboard 0 2 WITHSCORES
Get items ranked 2nd to 4th from 'products' sorted set.
Redis
ZRANGE products 1 3
Sample Program
First, we add 5 players with their scores to 'leaderboard'. Then we get the lowest 3 scores with ZRANGE and the highest 3 scores with ZREVRANGE, both showing scores.
Redis
ZADD leaderboard 100 "Alice" 200 "Bob" 150 "Charlie" 120 "Diana" 180 "Eve"
ZRANGE leaderboard 0 2 WITHSCORES
ZREVRANGE leaderboard 0 2 WITHSCORES
OutputSuccess
Important Notes
Indexes are inclusive, so stop index is included in the result.
If stop is -1, it means the last element in the sorted set.
Without WITHSCORES, only the items are returned, not their scores.
Summary
ZRANGE gets items from lowest to highest score by index range.
ZREVRANGE gets items from highest to lowest score by index range.
Use WITHSCORES to see the scores along with the items.