How to get highest score element of a sorted set – Redis ZPOPMAX | BZPOPMAX

1 week ago Lalit Bhagtani 0

In this tutorial, we will learn about how to remove and return the highest score element of the sorted set value stored at a key in redis datastore, by using redis ZPOPMAX and BZPOPMAX commands.

ZPOPMAX Command

This command removes and returns one or more highest score elements from the sorted set value stored at a specified key. The command takes count as an argument, which represents the total number of elements to be removed from the sorted set value. In case, if it is not specified, the default value of count is 1. When elements are returned, the one with the highest score will be the first, followed by the elements with lower scores.

The Error is returned, if a key exists but value stored at the key is not of the sorted set datatype and Nil is returned, if the key does not exist.

The syntax of Redis ZPOPMAX command is as follows :-

Syntax :-

redis host:post> ZPOPMAX <keyname> <count>

Output :-

- (array) reply, representing elements and scores of the sorted set.
- (nil), if key does not exists.
- Error, if key exist and value stored at the key is not a sorted set.

Example :-

Redis ZPOPMAX

BZPOPMAX Command

This command is a blocking version of ZPOPMAX command because it blocks the operation when there are no elements to pop from any of the specified sorted sets. In other words, it blocks the operation when all specified sorted sets are empty or all specified keys does not exist.

It removes and returns the highest score element from a first non-empty sorted set value, with the specified keys being checked from left to right. So for example, if command BZPOPMAX set1 set2 set3 0 is executed, where key set1 does not exist ( consider as an empty set ), set2 is an empty set and set3 contains three elements, then it removes and returns the highest score element of sorted set value stored at set3 as it is the first non empty set, when checking from set1 to set3.

This command takes timeout ( integer ) as an argument, which represents the maximum number of seconds to block. A timeout of zero can be used to block indefinitely.

The syntax of redis BZPOPMAX command is as follows :-

Syntax :-

redis host:post> BZPOPMAX <keyname> [ <keyname> ] <timeout>

Output :-

- (array) reply, three elements are returned where first element is name of the sorted set key, the 
  second element is the score of the popped element and third element is the popped element itself.
- (nil), when no element could be popped and timeout is expired.

Example :-

Redis BZPOPMAX

References :-

  1. ZPOPMAX Command Docs
  2. BZPOPMAX Command Docs

That’s all for how to remove and return the highest score element of the sorted set value stored in redis datastore. If you liked it, please share your thoughts in comments section and share it with others too.