How to pop & push an item from one to another list- Redis RPOPLPUSH | BRPOPLPUSH
2 months 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. For this, we will use Redis RPOPLPUSH and BRPOPLPUSH commands.
This command is used to remove and return the element from the tail ( end ) of the list value stored at source key and insert the same element at the head ( start ) of the list value stored at destination key. If the source key does not exist, nil value is returned and no operation is performed. If the destination key does not exist, it is first created as an empty list before performing the insert operation.
If the source and destination key are the same, then this operation is the 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.
This command is a blocking version of RPOPLPUSH command because it blocks the operation when there are no elements to pop from a 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 the client will get unblock to perform the RPOPLPUSH operation.
When a non-zero timeout is specified and the timeout has expired without insert operation against source key, then the client will get unblock returning a null value.
A timeout argument is an integer value representing a maximum number of seconds to block. A timeout of 0 seconds can be used to block indefinitely.
The syntax of the 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.