0
0
Redisquery~5 mins

ZRANK and ZREVRANK for position in Redis

Choose your learning style9 modes available
Introduction
ZRANK and ZREVRANK help you find the position of an item in a sorted list, so you know where it stands compared to others.
You want to see a player's rank in a game leaderboard.
You need to find the position of a product in a list sorted by price.
You want to check the order of tasks by priority in a to-do list.
You want to know the rank of a student based on their score.
You want to find the position of a word in a sorted dictionary.
Syntax
Redis
ZRANK key member
ZREVRANK key member
ZRANK returns the position of the member with scores ordered from low to high (0 is the top).
ZREVRANK returns the position with scores ordered from high to low (0 is the top).
Examples
Finds the rank of 'player1' in 'leaderboard' sorted from lowest to highest score.
Redis
ZRANK leaderboard player1
Finds the rank of 'player1' in 'leaderboard' sorted from highest to lowest score.
Redis
ZREVRANK leaderboard player1
Gets the position of 'item42' in the sorted set 'scores' from low to high.
Redis
ZRANK scores item42
Sample Program
We add three players with scores. Then we find player3's rank from low to high and from high to low.
Redis
ZADD leaderboard 100 player1 200 player2 150 player3
ZRANK leaderboard player3
ZREVRANK leaderboard player3
OutputSuccess
Important Notes
If the member does not exist, both commands return null (no rank).
Ranks start at 0, so the top item has rank 0.
ZRANK and ZREVRANK are fast even with many items.
Summary
ZRANK shows position with lowest score first (ascending).
ZREVRANK shows position with highest score first (descending).
Both help find where an item stands in a sorted set.