Skip to the workspace
Pebellslearn by building
Sorted Sets  ›  Lesson

ZRANK and ZREM

ZRANK 12 minZRANK gives a member's zero-based position counting from the lowest score, ZREVRANK counts from the highest, and ZREM removes members.

redis / ZRANK and ZREM

Explore each scene at your own pace.

01 · The rule

The rule

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) 1
  • ZRANK key member gives 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 member counts 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 member returns the score as a string.
  • ZREM key member [member ...] removes members and replies with how many were really there. priya was not, so only tom counted.

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.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.