In Redis, the ZREVRANK
command returns the rank of the specified element of a sorted set ordered in descending order (from high to low).
If we want the set to be in ascending order, we can use the ZRANK
command.
Syntax
The syntax goes like this:
ZREVRANK key member
Example
Suppose we create a sorted set like this:
ZADD scores 220 user:1 110 user:2 330 user:3 550 user:4 440 user:5 660 user:6
Result:
(integer) 6
In my case the sorted set didn’t exist, and so it was created and the six elements were added as specified.
Let’s now use the ZREVRANK
command to find out the score of a given member:
ZREVRANK scores user:3
Result:
(integer) 3
In this case, the element has a rank of 3
. The rank is zero based, and so this element is ranked fourth, based on the set being in descending order.
Let’s try another element:
ZREVRANK scores user:6
Result:
(integer) 0
This element has the highest score, and so we get zero. This is the lowest rank, based on the set being in descending order.
When the Element or Key Doesn’t Exist
If the element doesn’t exist we get nil
:
ZREVRANK scores user:10
Result:
(nil)
Same when the key doesn’t exist:
ZREVRANK oops user:10
Result:
(nil)