Redis ZPOPMAX Command Explained

In Redis, the ZMPOPMAX command removes and returns (pops) members with the highest scores from the specified sorted set. By default it pops one member, but we can also specify how many members we want to pop.

Syntax

The syntax goes like this:

ZPOPMAX key [count]

Example

Suppose we create the following sorted set:

ZADD cats 1 Meow 2 Fluffy 3 Scratch 4 Purr 5 Bite 6 Bunting

Let’s use the ZPOPMAX command to pop an element from that sorted set:

ZPOPMAX cats

Result:

1) "Bunting"
2) "6"

In this case I didn’t provide the count option, so it popped the member with the highest score.

Pop Multiple Elements

We can use the count option to pop multiple elements. By default, this is set to 1 but we can specify a different number.

ZPOPMAX cats 2

Result:

1) "Bite"
2) "5"
3) "Purr"
4) "4"

This time two members were popped because I specified a count of 2. When popping multiple members, the members are ordered from the highest score to the lowest.

Let’s take a look at the cats sorted set now:

ZRANGE cats 0 -1

Result:

1) "Meow"
2) "Fluffy"
3) "Scratch"

Now there’s only three elements left, because the others have been popped.

When the count Argument is Greater than the Sorted Set’s Cardinality

If the count argument is a larger number than the number of elements in the sorted set, then all elements are popped.

Example:

ZPOPMAX cats 10

Result:

1) "Scratch"
2) "3"
3) "Fluffy"
4) "2"
5) "Meow"
6) "1"

We can see that all elements were popped from our sorted set.

When the Key Doesn’t Exist

If the key doesn’t exist, we get an empty array:

ZPOPMAX oops

Result:

(empty array)

Wrong Data Type

When the key contains the wrong data type, an error is returned:

ZPOPMAX animals

Result:

(error) WRONGTYPE Operation against a key holding the wrong kind of value

In this case, the animals key contains a set (not a sorted set), and so we got an error.

We can use the TYPE command to check the key’s data type:

TYPE animals

Result:

set

As suspected, it’s a set.

Alternatives

  • Redis also has a ZMPOP command that can do the same thing as ZPOPMAX and more.
  • There’s also a ZPOPMIN command that works like ZPOPMAX, except that it pops the members with the highest scores instead of the lowest.
  • There’s also a BZPOPMAX command which is the blocking variant of ZPOPMAX.
  • There’s also a BZMPOP command which is the blocking variant of ZMPOP.
  • There’s also a BZPOPMIN command which is the blocking variant of ZPOPMIN.