In Redis, the RPUSH
command inserts one or more values into the tail of the list at the specified key.
If the key doesn’t exist, it is created as an empty list before performing the push operation. If the key already holds a value that is not a list, an error is returned.
Syntax
The syntax goes like this:
RPUSH 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
Here’s a basic example to demonstrate:
RPUSH scores 1 2 3
Result:
(integer) 3
In this case, the RPUSH
operation was successful, and so we got an integer reply with the length of the list after the push operation was performed.
We can now return all values from the list with the LRANGE
command:
LRANGE scores 0 -1
Result:
1) "1" 2) "2" 3) "3"
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 LPUSH
command, in which elements are inserted one after the other to the head of the list.
Here’s what happens when we push more elements to the list:
RPUSH scores 4 5 6
Result:
(integer) 6
This time we get an integer reply of 6
, because that’s how many elements are in the list after the push operation.
And here’s what happens when we use LRANGE
to get the values in the list:
LRANGE scores 0 -1
Result:
1) "1" 2) "2" 3) "3" 4) "4" 5) "5" 6) "6"
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:
RPUSH username 1 2 3
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).