In Redis, the ZREMRANGEBYRANK
command enables us to remove all members from a sorted set with a rank between a certain range.
Syntax
The syntax goes like this:
ZREMRANGEBYRANK key start stop
Example
Suppose we create a sorted set like this:
ZADD cats 15 Meow 27 Fluffy 43 Scratch 84 Purr 25 Bite 37 Bunting
In my case the sorted set didn’t exist, and so it was created and the members were added as specified.
We can use ZRANGE
to view all the contents of our sorted set, along with their scores:
ZRANGE cats 0 -1 WITHSCORES
Result:
1) "Meow" 2) "15" 3) "Bite" 4) "25" 5) "Fluffy" 6) "27" 7) "Bunting" 8) "37" 9) "Scratch" 10) "43" 11) "Purr" 12) "84"
Now let’s use the ZREMRANGEBYRANK
command to remove one or more of the members from that sorted set, based on its rank being in a certain range:
ZREMRANGEBYRANK cats 1 3
Result:
(integer) 3
The integer reply of 3
tells us that three elements were removed.
Let’s check the contents of the sorted set again:
ZRANGE cats 0 -1 WITHSCORES
Result:
1) "Meow" 2) "15" 3) "Scratch" 4) "43" 5) "Purr" 6) "84"
We can see that Bite
, Fluffy
, and Bunting
no longer exist in the sorted set.
Note that it’s the rank that we’re specifying, not the score. To remove members based on their score, we can use the ZREMRANGEBYSCORE
command.
Negative Indexes
We can use negative indexes to remove members with the highest rank.
Negative indexes work backwards from the highest rank. For example, an index of -1
is the last member, -2
is the second last, and so on.
Example:
ZREMRANGEBYRANK cats -2 -1
Result:
(integer) 2
Let’s check the remaining contents:
ZRANGE cats 0 -1
Result:
1) "Meow"
Only one member remains, and it’s the member that had the lowest rank. That’s because we removed the two highest members in our previous operation.
When the Key Doesn’t Exist
If the key doesn’t exist, no operation takes place and we get an integer reply of zero:
ZREMRANGEBYRANK oops 1 3
Result:
(integer) 0
This time nothing was removed, because the oops
key didn’t actually exist.
We can use the EXISTS
command to check for the existence of a key:
EXISTS oops
Result:
(integer) 0
An integer reply of zero means that it doesn’t exist.
Wrong Data Type
If the key exists, but it holds a different data type, an error occurs:
ZREMRANGEBYRANK animals 1 3
Result:
(error) WRONGTYPE Operation against a key holding the wrong kind of value
In this case, the animals
key holds a set (not a sorted set), and so an error occurred.
We can use the TYPE
command to check the key’s data type:
TYPE animals
Result:
set
As suspected, it’s a set.