How to remove & return last element of a list – Redis RPOP | BRPOP
4 weeks ago Lalit Bhagtani 0
In this tutorial, we will learn about how to remove and return the last element of the list value stored at a key in redis datastore, by using redis RPOP and BRPOP commands.
RPOP Command :-
This command is used to remove and return the last element of the list value stored at the specified key. Nil is returned, if key does not exist and error is returned, if key exist but value stored at the key is not of list datatype. The syntax of redis RPOP command is as follows :-
redis host:post> RPOP <keyname>
- (string) reply, representing last element of the list. - (nil), if key does not exists. - Error, if key exist and value stored at the key is not a list.
BRPOP Command :-
This command is a blocking version of RPOP 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 last element of a non-empty list value, with the specified keys being checked from from left to right. So for example, if command BRPOP 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 last 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, BRPOP 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 BRPOP 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 BRPOP command is as follows :-
redis host:post> BRPOP <keyname-1> [ <keyname> ] <timeout>
- (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.
That’s all for how to remove and return the last 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.