How to Use ZREVRANK in Redis: Syntax and Examples
Use the
ZREVRANK command in Redis to find the rank of a member in a sorted set, ordered from highest to lowest score. The command returns the zero-based rank of the member, or null if the member does not exist.Syntax
The ZREVRANK command syntax is:
ZREVRANK key member
Here, key is the name of the sorted set, and member is the element whose rank you want to find. The rank counts from 0 for the highest score.
redis
ZREVRANK mysortedset member1
Example
This example shows how to add members to a sorted set and then get the reverse rank of a member using ZREVRANK.
redis
127.0.0.1:6379> ZADD mysortedset 10 member1 (integer) 1 127.0.0.1:6379> ZADD mysortedset 20 member2 (integer) 1 127.0.0.1:6379> ZADD mysortedset 15 member3 (integer) 1 127.0.0.1:6379> ZREVRANK mysortedset member3 (integer) 1 127.0.0.1:6379> ZREVRANK mysortedset member1 (integer) 2 127.0.0.1:6379> ZREVRANK mysortedset member4 (nil)
Output
(integer) 1
(integer) 1
(integer) 1
(integer) 1
(integer) 2
(nil)
Common Pitfalls
Common mistakes when using ZREVRANK include:
- Using the wrong key type (the key must be a sorted set).
- Expecting ranks to start at 1 instead of 0.
- Not handling
nullresults when the member does not exist.
Always check if the result is null before using the rank.
python
127.0.0.1:6379> ZREVRANK mysortedset member5 (nil) # Correct handling in application code: if rank is None: print("Member not found in sorted set") else: print(f"Rank is {rank}")
Output
(nil)
Quick Reference
| Command | Description |
|---|---|
| ZREVRANK key member | Returns the rank of member in sorted set ordered from highest to lowest score |
| Returns integer | Zero-based rank if member exists |
| Returns nil | If member does not exist in the sorted set |
| Key type | Must be a sorted set |
Key Takeaways
ZREVRANK returns the zero-based rank of a member ordered from highest to lowest score in a sorted set.
If the member does not exist, ZREVRANK returns null (nil).
The key must be a sorted set; otherwise, the command will error.
Ranks start at 0 for the highest score, not 1.
Always check for null results to avoid errors in your application.