In Redis, the LPUSHX
command inserts one or more values into the head 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:
LPUSHX key element [element ...]
Where each element
becomes an element in the list. Elements are inserted one after the other to the head 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) "3" 2) "2" 3) "1"
We can use the LPUSHX
command to push new values to that list:
LPUSHX scores 4 5 6
Result:
(integer) 6
In this case, the LPUSHX
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) "6" 2) "5" 3) "4" 4) "3" 5) "2" 6) "1"
As mentioned, list elements are inserted one after the other to the head of the list, from the leftmost element to the rightmost element. Therefore our list goes 6, 5, 4, 3, 2, 1 instead of 1, 2, 3, 4, 5, 6. Use RPUSHX
to have them inserted in the opposite order.
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:
LPUSHX 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).
When the Key Doesn’t Exist
If the key doesn’t exist, no operation is performed:
Example:
LPUSHX nonexistentkey 1 2 3
Result:
(integer) 0