In Redis, the BZPOPMAX
command is the blocking variant of the ZPOPMAX
command.
The BZPOPMAX
command works similar to ZPOPMAX
when any of the sorted sets contain elements. That is, it pops a member with the highest score from the sorted set.
More specifically, BZPOPMAX
pops a member with the highest score from the first non-empty sorted set, with the given keys being checked in the order that they are given.
However, if all of the specified sorted sets are empty, then BZPOPMAX
will block the connection until another client adds members to one of the keys or until the specified timeout elapses. It’s possible to block the connection indefinitely by using a timeout of zero.
One other difference between BZPOPMAX
and ZPOPMAX
is that (at least at the the time of writing), the BZPOPMAX
command accepts multiple keys whereas the ZPOPMAX
command accepts just one.
Syntax
The syntax for BZPOPMAX
goes like this:
BZPOPMAX key [key ...] timeout
Example
Here’s an example of what happens when all keys we pass to the BZPOPMAX
command contain empty sorted sets:
BZPOPMAX birds cats 2
Result:
(nil) (2.09s)
Here, I provided a timeout of 2
, which means that it waits for two seconds if all sorted sets are empty. We can see by the result that it took 2.04 seconds to run, and the result of the operation is nil
.
Passing a timeout
argument of 0
(zero) blocks the connection indefinitely.
This blocking feature is what distinguishes BZPOPMAX
from ZPOPMAX
. The ZPOPMAX
command would simply return nil
without waiting.
When the Key is Not Empty
When there’s a key that contains a non-empty sorted set, BZPOPMAX
works like ZPOPMAX
, in that it returns the result immediately without waiting. In the above example, both the birds
and the cats
keys didn’t exist. Let’s create one called cats
:
ZADD cats 1 Meow 2 Fluffy 3 Scratch 4 Purr 5 Bite 6 Bunting
Now let’s run BZPOPMAX
again:
BZPOPMAX birds cats 2
Result:
1) "cats" 2) "Bunting" 3) "6"
This time my results were returned immediately. There was no waiting period like in the previous example.
Here I provided two sorted sets; birds
and cats
. The birds
key didn’t exist and so it was treated as an empty sorted set. The cats
key did exist with a sorted set, and so the operation was performed against that key.
Let’s take a look at the cats
sorted set now:
ZRANGE cats 0 -1
Result:
1) "Meow" 2) "Fluffy" 3) "Scratch" 4) "Purr" 5) "Bite"
We can see that Bunting
no longer exists in the sorted set.
Wrong Data Type
When the key contains the wrong data type, an error is returned:
BZPOPMAX countries 1
Result:
(error) WRONGTYPE Operation against a key holding the wrong kind of value
In this case, the countries
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 countries
Result:
set
As suspected, it’s a set.