How to pop & push an item from one to another list- Redis RPOPLPUSH | BRPOPLPUSH
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 one key and insert the same element at first position of the list value stored at another key in redis datastore, by using redis RPOPLPUSH and BRPOPLPUSH commands.
RPOPLPUSH Command :-
This command is used to remove and return the element from tail ( end ) of the list value stored at source key and insert the same element at head ( start ) of the list value stored at destination key.
If source key does not exist, nil value is returned and no operation is performed. If destination key does not exist, it is first created as an empty list before performing the insert operation.
If source and destination key are same, then this operation is same as rotating the list elements.
The syntax of redis RPOPLPUSH command is as follows :-
redis host:post> RPOPLPUSH <keyname-source> <keyname-destination>
- (string) reply, representing popped element of the source list. - (nil), if source key does not exists. - Error, if source or destination key exist and value stored at the key is not a list.
BRPOPLPUSH Command :-
This command is a blocking version of RPOPLPUSH command because it blocks the operation when there is no elements to pop from source list value. In other words, it blocks the operation when list value at source key is empty or source key does not exist.
When another client executes a command like LPUSH, RPUSH and LINSERT to insert an element in source list value, then client will get unblock to perform the RPOPLPUSH operation.
When non-zero timeout is specified and timeout has expired without insert operation against source key, then client will get unblock returning null value.
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 BRPOPLPUSH command is as follows :-
redis host:post> BRPOPLPUSH <keyname-source> <keyname-destination> <timeout>
- (string) reply, representing popped element of the source list. - (nil) reply, when no element could be popped and timeout is expired.
If you liked it, please share your thoughts in comments section and share it with others too.