How to Use APPEND Command in Redis for String Manipulation
Use the
APPEND command in Redis to add a string to the end of an existing string value stored at a key. If the key does not exist, APPEND creates it with the given value. The command returns the new length of the string after appending.Syntax
The APPEND command syntax is simple:
APPEND key value
Here, key is the name of the string key you want to append to, and value is the string you want to add at the end.
If the key does not exist, Redis creates it with the value as its content.
The command returns the length of the string after the append operation.
redis
APPEND mykey "Hello" APPEND mykey " World"
Output
5
11
Example
This example shows how to append strings to a Redis key and check the resulting length and value.
redis
127.0.0.1:6379> SET greeting "Hello" OK 127.0.0.1:6379> APPEND greeting " World" 11 127.0.0.1:6379> GET greeting "Hello World"
Output
OK
11
"Hello World"
Common Pitfalls
Common mistakes when using APPEND include:
- Trying to append to a key holding a non-string type, which causes an error.
- Assuming
APPENDreplaces the string instead of adding to it. - Not checking the returned length, which can help verify the operation succeeded.
Example of wrong usage and correction:
redis
127.0.0.1:6379> LPUSH mylist "item" (integer) 1 127.0.0.1:6379> APPEND mylist "more" (error) WRONGTYPE Operation against a key holding the wrong kind of value # Correct approach: 127.0.0.1:6379> SET mystring "start" OK 127.0.0.1:6379> APPEND mystring " more" 10
Output
(integer) 1
(error) WRONGTYPE Operation against a key holding the wrong kind of value
OK
10
Quick Reference
| Command | Description | Return Value |
|---|---|---|
| APPEND key value | Add value to end of string at key | New length of string |
| GET key | Retrieve the string value stored at key | String value or nil |
| SET key value | Set key to hold the string value | OK |
Key Takeaways
APPEND adds data to the end of a string key or creates the key if it doesn't exist.
The command returns the new length of the string after appending.
APPEND only works on string keys; using it on other types causes errors.
Always check the returned length to confirm the append succeeded.
Use GET to verify the final string content after appending.