Redis ZREMRANGEBYSCORE Command Explained

In Redis, the ZREMRANGEBYSCORE command enables us to remove all members from a sorted set with a score between a certain range.

Syntax

The syntax goes like this:

ZREMRANGEBYSCORE key min max

Where min is the minimum score and max is the maximum score of the range.

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 ZREMRANGEBYSCORE command to remove one or more of the members from that sorted set, based on its score being in a certain range:

ZREMRANGEBYSCORE cats 25 40

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 score that we’re specifying, not the rank. To remove members based on their score, we can use the ZREMRANGEBYRANK command.

When the Key Doesn’t Exist

If the key doesn’t exist, no operation takes place and we get an integer reply of zero:

ZREMRANGEBYSCORE oops 25 40

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:

ZREMRANGEBYSCORE animals 25 40

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.