How to Use ZRANK in Redis: Syntax and Examples
Use the
ZRANK command in Redis to get the rank (index) of a member in a sorted set, where ranks start at 0 for the lowest score. The syntax is ZRANK key member, and it returns the rank or null if the member does not exist.Syntax
The ZRANK command syntax is:
ZRANK key member
Here:
- key: The name of the sorted set.
- member: The element whose rank you want to find.
The command returns the zero-based rank of the member in the sorted set ordered by score from lowest to highest. If the member is not found, it returns null.
redis
ZRANK mysortedset member1
Example
This example shows how to add members to a sorted set and then get the rank of a specific member using ZRANK.
redis
127.0.0.1:6379> ZADD mysortedset 10 "apple" (integer) 1 127.0.0.1:6379> ZADD mysortedset 20 "banana" (integer) 1 127.0.0.1:6379> ZADD mysortedset 15 "cherry" (integer) 1 127.0.0.1:6379> ZRANK mysortedset "cherry" (integer) 1 127.0.0.1:6379> ZRANK mysortedset "banana" (integer) 2 127.0.0.1:6379> ZRANK mysortedset "orange" (nil)
Output
(integer) 1
(integer) 2
(nil)
Common Pitfalls
Common mistakes when using ZRANK include:
- Using
ZRANKon a key that is not a sorted set, which causes an error. - Expecting ranks to start at 1 instead of 0.
- Not handling the
nullresult when the member does not exist in the set. - Confusing
ZRANK(ascending order) withZREVRANK(descending order).
Always check if the result is null before using the rank value.
redis
127.0.0.1:6379> ZRANK mysortedset "orange" (nil) -- Correct handling in application pseudocode: if rank == null then print("Member not found in sorted set") else print("Rank is " .. rank) end
Output
(nil)
Quick Reference
| Command | Description |
|---|---|
| ZRANK key member | Returns the rank of member in sorted set (0-based, ascending score) |
| ZREVRANK key member | Returns the rank of member in sorted set (0-based, descending score) |
| ZADD key score member | Adds member with score to sorted set |
| ZRANGE key start stop | Returns members in rank range |
Key Takeaways
ZRANK returns the zero-based rank of a member in a sorted set ordered by ascending score.
If the member does not exist, ZRANK returns null, so always check for this case.
ZRANK only works on sorted sets; using it on other types causes errors.
Ranks start at 0, so the lowest score member has rank 0.
Use ZREVRANK to get ranks ordered by descending score.