Redis RPUSHX Command Explained

In Redis, the RPUSHX command inserts one or more values into the tail of the list at the specified key, but only if the key exists and it contains a list.

If the key doesn’t exist, no operation is performed. If the key exists but it doesn’t contain a list, an error is returned.

Syntax

The syntax goes like this:

RPUSHX key element [element ...]

Where each element becomes an element in the list. Elements are inserted one after the other to the tail of the list, from the leftmost element to the rightmost element.

Example

Suppose we have the following list called scores:

LRANGE scores 0 -1

Result:

1) "1"
2) "2"
3) "3"

We can use the RPUSHX command to push new values to the tail of that list:

RPUSHX scores 4 5 6

Result:

(integer) 6

In this case, the RPUSHX operation was successful, and so we got an integer reply with the length of the list after the push operation was performed. The list now holds 6 elements, and so the integer reply is 6.

We can again return all current values from the list with the LRANGE command:

LRANGE scores 0 -1

Result:

1) "1"
2) "2"
3) "3"
4) "4"
5) "5"
6) "6"

As mentioned, list elements are inserted one after the other to the tail of the list, from the leftmost element to the rightmost element. This is in contrast to the LPUSHX and LPUSH commands, in which elements are inserted one after the other to the head of the list.

When the Key Doesn’t Contain a List

If the key already exists but it doesn’t contain a list, an error is returned.

Example:

RPUSHX username 7 8 9

Result:

(error) WRONGTYPE Operation against a key holding the wrong kind of value

We can use the TYPE command to find out the type of value that this key is holding:

TYPE username

Result:

string

In this case the key holds a string (which is not a list).

When the Key Doesn’t Exist

If the key doesn’t exist, no operation is performed:

Example:

RPUSHX nonexistentkey 1 2 3

Result:

(integer) 0