How to insert element at tail of list value – Redis RPUSH | RPUSHX

4 weeks ago Lalit Bhagtani 0

In this tutorial, we will learn about how to insert one or more elements at the tail of the list value stored at a key in redis datastore, by using redis RPUSH and RPUSHX commands.

RPUSH Command :-

The RPUSH command is used to insert one or more specified elements at the tail ( end ) of the list value stored at the key. Elements are inserted one after another to the tail of the list value, from the leftmost element to the rightmost element. So for example, if command RPUSH list a b c is executed, then list will contain a as first element, b as second element and c as third element.

If the key does not exist, it is first created as an empty list before performing the insert operation. If the key exist but value stored at the key is not of list datatype, then error is returned. The syntax of redis RPUSH command is as follows :-

Syntax :-

redis host:post> RPUSH <keyname> <value 1> [ <value> ]

Output :-

- (integer) reply, representing the number of elements in the list.
- Error, if key exist and value stored at the key is not a list.

Example :-

Redis RPUSH

 

RPUSHX Command :-

The RPUSHX command is used to insert only one specified element at the tail ( end ) of the list value stored at the key. No operation is performed and o is returned, if the key does not exist. If the key exist but value stored at the key is not of list datatype, then error is returned. The syntax of redis RPUSHX command is as follows :-

Syntax :-

redis host:post> RPUSHX <keyname> <value>

Output :-

- (integer) reply, representing the number of elements in the list.
- Error, if key exist and value stored at the key is not a list.

Example :-

Redis RPUSHX

References :-

  1. RPUSH Command Docs
  2. RPUSHX Command Docs

That’s all for how to insert one or more elements at the tail 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.