ZRANK and ZREM
When Asha opens Wordcraft, her screen says "You are #2 of 4". Finding that number by fetching the whole leaderboard and counting would be wasteful. Redis already knows every member's position, and it can also drop a player who leaves the game.
The rule
ZRANK counts from the bottom, ZREVRANK from the top; both start at 0.
The leaderboard holds tom 90, ravi 150, asha 320 and meera 410.
127.0.0.1:6379> ZRANK leaderboard asha
(integer) 2
127.0.0.1:6379> ZREVRANK leaderboard asha
(integer) 1
127.0.0.1:6379> ZSCORE leaderboard asha
"320"
127.0.0.1:6379> ZRANK leaderboard priya
(nil)
127.0.0.1:6379> ZREM leaderboard tom priya
(integer) 1
127.0.0.1:6379> ZREVRANK leaderboard asha
(integer) 1ZRANK key membergives the member's position counting from the lowest score, starting at 0. Asha has two players below her, so she is rank 2.ZREVRANK key membercounts from the highest score. Only Meera is above Asha, so she is rank 1. For a leaderboard this is the one you want; add 1 to show "#2".- A member that is not in the set gives
(nil). ZSCORE key memberreturns the score as a string.ZREM key member [member ...]removes members and replies with how many were really there.priyawas not, so onlytomcounted.
Removing Tom did not change Asha's ZREVRANK, because Tom was below her. Removing someone above her would move her up. Since Redis 7.2, ZRANK and ZREVRANK also accept WITHSCORE to return the rank and the score together.
The shortcut
To find a rank fast, count the members on the far side of the player: for ZRANK, how many have a lower score; for ZREVRANK, how many have a higher score. That count is the rank.
The set
Scores: tom 90, ravi 150, asha 320, meera 410.
The off-by-one trap: showing the raw rank as the place. The leader has rank 0, not rank 1.
Drills
Answer fast — trust the rule.
With tom 90, ravi 150, asha 320, meera 410, what does ZRANK leaderboard meera reply?
Same set. What does ZREVRANK leaderboard meera reply?
What does ZREM leaderboard zoe reply when zoe is not a member?
From tom 90, ravi 150, asha 320, meera 410, you run ZREM leaderboard meera. What does ZREVRANK leaderboard ravi reply now?
Remember
- ZRANK counts from the bottom, ZREVRANK from the top; both start at 0.
- The rank equals the number of members on the far side of the player.
- Show rank + 1 as the place, and expect nil for a missing member.
