Redis ZREM Command Explained

In Redis, the ZREM command removes one or more members from the specified sorted set.

Syntax

The syntax goes like this:

ZREM key member [member ...]

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 six elements were added as specified.

We can use ZRANGE to view all the contents of our sorted set:

ZRANGE cats 0 -1

Result:

1) "Meow"
2) "Bite"
3) "Fluffy"
4) "Bunting"
5) "Scratch"
6) "Purr"

Now let’s use the ZREM command to remove one or more of those members from the sorted set:

ZREM cats "Bite" "Scratch"

Result:

1) "Meow"
2) "Bite"
3) "Fluffy"
4) "Bunting"
5) "Scratch"
6) "Purr"

Result:

(integer) 2

The integer reply of 2 tells us that two elements were removed.

Let’s check the contents of the sorted set again:

ZRANGE cats 0 -1

Result:

1) "Meow"
2) "Fluffy"
3) "Bunting"
4) "Purr"

As expected, the two members were removed as specified.

When the Member Doesn’t Exist

If the specified member doesn’t exist in the sorted set, it’s ignored:

ZREM cats "Meow" "Scratch"

Result:

(integer) 1

This time only one member was removed even though I specified two. That’s because the second one (Scratch) had already been removed in the previous example.

Let’s check the contents again:

ZRANGE cats 0 -1

Result:

1) "Fluffy"
2) "Bunting"
3) "Purr"

This time Meow has been removed as specified.

When the Key Doesn’t Exist

If the key doesn’t exist it’s ignored:

ZREM dogs "Meow" "Scratch"

Result:

(integer) 0

This time nothing was removed, because the dogs key didn’t actually exist.

We can use the EXISTS command to check for the existence of a key:

EXISTS dogs

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:

ZREM animals "Meow" "Scratch"

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.