Redis LINSERT Command Explained

In Redis, the LINSERT command allows us to insert an element into a list.

We have the choice of inserting it either before or after a specified element.

Syntax

The syntax goes like this:

LINSERT key <BEFORE | AFTER> pivot element

Example

Suppose we create a list like this:

RPUSH animals Cat Dog Horse

Result:

(integer) 3

Let’s take a look at the list:

LRANGE animals 0 -1

Result:

1) "Cat"
2) "Dog"
3) "Horse"

We can now use the LINSERT command to insert a value into the list:

LINSERT animals BEFORE "Horse" "Zebra"

Result:

(integer) 4

The result is an integer reply of 4, which means that the list now contains four items.

Now let’s take another look at the list:

LRANGE animals 0 -1

Result:

1) "Cat"
2) "Dog"
3) "Zebra"
4) "Horse"

We can see that Zebra has been inserted before Horse as specified.

Here’s another example, this time we use the AFTER keyword to insert the value after a given value:

LINSERT animals AFTER "Cat" "Rhino"

Result:

(integer) 5

This time we get an integer reply of 5, which means that the list now contains five elements.

Now let’s check the list again:

LRANGE animals 0 -1

Result:

1) "Cat"
2) "Rhino"
3) "Dog"
4) "Zebra"
5) "Horse"

We can see that Rhino has been inserted after Cat as specified.

When the Specified Value Doesn’t Exist

When we try to insert a value before or after a value that doesn’t exist, the value isn’t inserted and we get an integer reply of -1:

LINSERT animals AFTER "Mouse" "Bull"

Result:

(integer) -1

In this case, the list doesn’t contain Mouse, and so nothing was inserted and we got an integer reply of -1.

Now if we take a look the list, we see that the value hasn’t been inserted:

LRANGE animals 0 -1

Result:

1) "Cat"
2) "Rhino"
3) "Dog"
4) "Zebra"
5) "Horse"

Non-Existent Key

If the key doesn’t exist, it’s treated as an empty list and no operation is performed:

LINSERT nonexistentkey AFTER "Dog" "Monkey"

Result:

(integer) 0