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.