How to insert element at head of list value – Redis LPUSH | LPUSHX

2 months ago Lalit Bhagtani 0

In this tutorial, we will learn about how to insert one or more elements at the head of the list value stored at a key in redis datastore. For this, we will use Redis LPUSH and LPUSHX commands.

LPUSH Command

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

If the key does not exists, 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 an error is returned. The syntax of Redis LPUSH command is as follows :-

Syntax :-

redis host:post> LPUSH <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 LPUSH

LPUSHX Command

The LPUSHX command is used to insert only one specified element at the head ( start ) 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 exists but value stored at the key is not of list datatype, then an error is returned. The syntax of the Redis LPUSHX command is as follows :-

Syntax :-

redis host:post> LPUSHX <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 LPUSHX

References :-

  1. LPUSH Command Docs
  2. LPUSHX Command Docs

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