0
0
Redisquery~5 mins

Top-N queries in Redis

Choose your learning style9 modes available
Introduction
Top-N queries help you find the highest or lowest N items from a list, like the top 5 scores or best-selling products.
Showing the top 3 players with the highest scores in a game.
Finding the 10 most popular products in an online store.
Listing the 5 most recent posts with the most likes.
Getting the top 7 cities with the highest temperatures today.
Syntax
Redis
ZRANGE key start stop [WITHSCORES]
ZREVRANGE key start stop [WITHSCORES]
ZRANGE returns items in ascending order (lowest to highest score).
ZREVRANGE returns items in descending order (highest to lowest score).
Examples
Get the bottom 5 items with their scores from the sorted set 'leaderboard'.
Redis
ZRANGE leaderboard 0 4 WITHSCORES
Get the top 3 items with their scores from the sorted set 'leaderboard'.
Redis
ZREVRANGE leaderboard 0 2 WITHSCORES
Sample Program
Add 5 players with scores to 'leaderboard'. Then get the top 3 players with highest scores.
Redis
ZADD leaderboard 100 Alice 200 Bob 150 Carol 180 Dave 120 Eve
ZREVRANGE leaderboard 0 2 WITHSCORES
OutputSuccess
Important Notes
Sorted sets in Redis store members with scores, allowing easy Top-N queries.
Indexes start at 0, so 0 2 means first 3 items.
WITHSCORES option returns both member and its score.
Summary
Top-N queries find the highest or lowest N items in a sorted set.
Use ZREVRANGE for top scores (descending order).
Use ZRANGE for lowest scores (ascending order).