Redis ZREMRANGEBYLEX Command Explained

In Redis, the ZREMRANGEBYLEX command enables us to use a lexicographical range to remove members from a sorted set. That is, we can specify that all members between a given lexicographical range are removed.

This relies on all members having the same score (which forces lexicographical ordering).

Syntax

The syntax goes like this:

ZREMRANGEBYLEX key min max

Example

Suppose we create a sorted set like this:

ZADD users 0 Ann 0 Bev 0 Cath 0 Dave 0 Eve 0 Faith 0 Gav

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:

ZRANGE users 0 -1

Result:

1) "Ann"
2) "Bev"
3) "Cath"
4) "Dave"
5) "Eve"
6) "Faith"
7) "Gav"

Now let’s use the ZREMRANGEBYLEX command to remove one or more of those members from that sorted set, based on a lexicographical range:

ZREMRANGEBYLEX users [Cath [Eve

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 users 0 -1

Result:

1) "Ann"
2) "Bev"
3) "Faith"
4) "Gav"

When using this command, the two arguments that specify the range must start with ( or [, in order to specify whether the range interval is exclusive or inclusive. In the above example I used [ to specify an inclusive range.

The special values of + and - mean positive and negative infinite strings. This enables us to remove all members from the sorted set (assuming they have the same score).

Let’s run the command again, this time with an exclusive range:

ZREMRANGEBYLEX users (Ann (Gav

Result:

(integer) 2

And let’s check the remaining contents:

ZRANGE users 0 -1

Result:

1) "Ann"
2) "Gav"

Both Ann and Gav remain in the sorted set despite the fact that we specified those exact names in our range. That’s because we made it an exclusive range, which excluded those two names from the removal.

When the Key Doesn’t Exist

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

ZREMRANGEBYLEX oops (Ann (Gav

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:

ZREMRANGEBYLEX animals (Ann (Gav

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.