Redis LMOVE Command Explained

In Redis, the LMOVE command atomically returns and removes either the first or last element of the given source list, and pushes the element at either the first or last element of the specified destination list.

Whether it’s the first or last element depends on the arguments passed to the command.

The LMOVE command can be used in place of the RPOPLPUSH command, which has been deprecated since Redis 6.2.0.

Syntax

The syntax goes like this:

LMOVE source destination LEFT | RIGHT LEFT | RIGHT

Where source is the source list and destination is the destination list.

The other arguments determine whether the command removes/pushes the first or last element from/to the lists.

Example

Suppose we create a list like this:

RPUSH scores 1 2 3 4 5 6 7 8 9 10

Result:

(integer) 10

Let’s look at its contents:

LRANGE scores 0 -1

Result:

 1) "1"
 2) "2"
 3) "3"
 4) "4"
 5) "5"
 6) "6"
 7) "7"
 8) "8"
 9) "9"
10) "10"

We can use LMOVE like this:

LMOVE scores points LEFT RIGHT

Result:

"1"

The result shows us the value that was moved from the source list to the destination list.

Let’s check the contents of our list again to verify:

LRANGE scores 0 -1

Result:

1) "2"
2) "3"
3) "4"
4) "5"
5) "6"
6) "7"
7) "8"
8) "9"
9) "10"

We can see that the first element has gone.

Let’s check the destination list:

LRANGE points 0 -1

Result:

1) "1"

The element has turned up in the destination list.

In my case, the destination list didn’t previously exist. Therefore it was created, and the element was pushed to it.

Let’s try LMOVE again, this time using different arguments:

LMOVE scores points RIGHT LEFT

Result:

"10"

This time I used RIGHT LEFT instead of LEFT RIGHT. In this case the last element is removed, and it’s pushed as the first element to the destination list.

Let’s check the lists again.

LRANGE scores 0 -1

Result:

1) "2"
2) "3"
3) "4"
4) "5"
5) "6"
6) "7"
7) "8"
8) "9"

This time the last element has gone.

And the destination list:

LRANGE points 0 -1

Result:

1) "10"
2) "1"

The element is now in the destination list.

Circular Lists

It’s possible to use the same list as both the source and the destination. This allows the client to visit all the elements in a list without having to transfer the whole list from the server to the client using the LRANGE operation.

Here’s an example of using the same list for the source and the destination:

LMOVE scores scores RIGHT LEFT

Result:

"9"

Now let’s check the list:

LRANGE scores 0 -1

Result:

1) "9"
2) "2"
3) "3"
4) "4"
5) "5"
6) "6"
7) "7"
8) "8"

We can see that the last element has now become the first.

See the Redis documentation for more information about this technique and the command in general.