How to remove & return first element of a list – Redis LPOP | BLPOP

5 years ago Lalit Bhagtani 0

In this tutorial, we will learn about how to remove and return the first element of the list value stored at a key in redis datastore. For this, we will use redis LPOP and BLPOP commands.

LPOP Command

This command is used to remove and return the first element of the list value stored at the specified key. Nil is returned, if a key does not exist and an error is returned, if the key exists but value stored at the key is not of list datatype. The syntax of the Redis LPOP command is as follows :-

Syntax :-

redis host:post> LPOP <keyname>

Output :-

- (string) reply, representing first element of the list.
- (nil), if key does not exists.
- Error, if key exist and value stored at the key is not a list.

Example :-

Redis LPOP

BLPOP Command

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

It removes and returns the first element of a non-empty list value, with the specified keys being checked from from left to right. So for example, if command BLPOP list1 list2 list3 0 is executed, where key list1 does not exist ( consider as an empty list ), list2 is an empty list and list3 contains three elements, then it removes and returns the first element of list value stored at list3 as it is the first non empty list, when checking from list1 to list3.

If either the specified key does not exist or specified key’s list value is empty, BLPOP blocks the operation until another client executes a command like LPUSH, RPUSH, and LINSERT to insert an element in one of the specified key. Once new element is present on one of the list values, client returns with the name of the key unblocking it and the popped value.

When BLPOP causes a client to block and a non-zero timeout is specified, the client will unblock returning nil value when the specified timeout has expired without a insert operation against at least one of the specified keys.

A timeout argument is an integer value representing maximum number of seconds to block. A timeout of 0 seconds can be used to block indefinitely.

The syntax of Redis BLPOP command is as follows :-

Syntax :-

redis host:post> BLPOP <keyname-1> [ <keyname> ] <timeout>

Output :-

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

Example :-

Redis BLPOP

References :-

  1. LPOP Command Docs
  2. BLPOP Command Docs

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

<- List Commands