How to Use RPUSH in Redis: Syntax and Examples
Use the
RPUSH command in Redis to add one or more elements to the end of a list stored at a key. If the list does not exist, RPUSH creates it before adding the elements.Syntax
The RPUSH command adds one or more values to the end of a list stored at a given key.
- key: The name of the list.
- value [value ...]: One or more values to append to the list.
If the key does not exist, Redis creates a new list before adding the values.
redis
RPUSH key value [value ...]
Example
This example shows how to add elements to a list named fruits using RPUSH. It adds "apple", "banana", and "cherry" to the list.
redis
127.0.0.1:6379> RPUSH fruits apple banana cherry (integer) 3 127.0.0.1:6379> LRANGE fruits 0 -1 1) "apple" 2) "banana" 3) "cherry"
Output
(integer) 3
1) "apple"
2) "banana"
3) "cherry"
Common Pitfalls
Common mistakes when using RPUSH include:
- Using
RPUSHon a key that holds a non-list type, which causes an error. - Expecting
RPUSHto add elements to the start of the list (useLPUSHinstead). - Not checking the return value, which shows the new length of the list after the push.
redis
127.0.0.1:6379> SET mykey "hello" OK 127.0.0.1:6379> RPUSH mykey world (error) WRONGTYPE Operation against a key holding the wrong kind of value -- Correct usage: 127.0.0.1:6379> RPUSH mylist world (integer) 1
Output
(error) WRONGTYPE Operation against a key holding the wrong kind of value
(integer) 1
Quick Reference
| Command | Description | Return Value |
|---|---|---|
| RPUSH key value [value ...] | Add one or more elements to the end of the list | New length of the list (integer) |
| LPUSH key value [value ...] | Add elements to the start of the list | New length of the list (integer) |
| LRANGE key start stop | Get elements from the list between start and stop indexes | List of elements |
Key Takeaways
RPUSH adds elements to the end of a Redis list and creates the list if it doesn't exist.
The command returns the new length of the list after adding the elements.
Using RPUSH on a key holding a non-list type causes an error.
To add elements to the start of a list, use LPUSH instead of RPUSH.
Always check the return value to confirm the list length after the operation.