In Redis, the APPEND
command appends a given value to the end of the value of a specified key.
If the key doesn’t exist, APPEND
creates the key with the empty string and appends the value to it (so it basically works like the SET
command in this case).
Syntax
APPEND key value
Where key
is the key to append to, and value is the value
to append.
Example
Suppose we set a key like this:
SET pets "Cat"
Result:
OK
Let’s quickly take a look at it:
GET pets
Result:
"Cat"
OK, now let’s append a value to it:
APPEND pets " Dog"
Result:
(integer) 7
In this case we get an integer reply of 7
, which is the length of the string after the APPEND
operation was performed.
Now let’s check the value of the pets
key:
GET pets
Result:
"Cat Dog"
Our new string has been appended.
Note that the only reason there’s a space between the two values is because I included a space at the left of the string to be appended. If I hadn’t done that, the two strings would have been joined with no space between them.
Extract a Value
We can use the GETRANGE
command to extract a specified part of the value of a given key. Therefore, if we’ve appended multiple values to a string, and we know how long they are, we can use GETRANGE
to extract a value based on its position in the overall string:
GETRANGE pets 4 6
Result:
"Dog"
When the Key Doesn’t Exist
As mentioned, if the key doesn’t exist, APPEND
creates the key with the empty string and appends the value to it (so it basically works like the SET
command).
Example:
APPEND newkey "Dog"
Result:
(integer) 3
Let’s check the value of the newkey
key:
GET newkey
Result:
"Dog"