How to get lowest score element of a sorted set – Redis ZPOPMIN | BZPOPMIN

5 years ago Lalit Bhagtani 0

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

ZPOPMIN Command

This command removes and returns one or more lowest 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 lowest score will be the first, followed by the elements with higher 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 ZPOPMIN command is as follows :-

Syntax :-

redis host:post> ZPOPMIN <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 ZPOPMIN

BZPOPMIN Command

This command is a blocking version of ZPOPMIN 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 lowest 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 BZPOPMIN 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 lowest 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 BZPOPMIN command is as follows :-

Syntax :-

redis host:post> BZPOPMIN <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 BZPOPMIN

References :-

  1. ZPOPMIN Command Docs
  2. BZPOPMIN Command Docs

That’s all for how to remove and return the lowest 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.