In Redis, the COPY
command copies the value from one key to another.
This command was introduced in Redis 6.2.0.
Syntax
The syntax goes like this:
COPY source destination [DB destination-db] [REPLACE]
Where source
is the key that contains the value to copy, and destination
is the key to copy it to.
The [DB destination-db]
part means that we can optionally specify an alternative logical database index for the destination key. By default, the destination key is created in the logical database used by the connection.
The [REPLACE]
part means that we can optionally specify REPLACE
to remove the destination key before copying the value to it.
Example
Suppose we set a value:
SET key1 "Dog"
Result:
OK
Now let’s use the COPY
command to copy that value to a new key:
COPY key1 key2
Result:
(integer) 1
We get an integer reply of 1
, which means that the new key was created and the value was copied.
An integer reply of 0
would mean that it wasn’t copied.
Now let’s check the value of the new key:
GET key2
Result:
"Dog"
As expected, it’s the same value that’s stored in the source key.
Bear in mind that the source key still holds the same value:
GET key1
Result:
"Dog"
When the Destination Key Already Exists
By default, if the destination key already exists, the value is not copied, and we get an integer reply of 0
. However, this can be changed by using the REPLACE
option.
To test this, let’s change the value of the source key, then try the COPY
operation again.
Change the value of the source key:
SET key1 "Cat"
Result:
OK
Now try to copy that key’s value:
COPY key1 key2
Result:
(integer) 0
We get an integer reply of 0
, which means that the value wasn’t copied.
We can verify this by checking the value of key2
:
GET key2
Result:
"Dog"
It’s still the same value that was set previously.
The REPLACE
Option
We can use the REPLACE
argument to remove the destination key before copying the value to it. This effectively allows us to copy the value to a key that already exists.
Example:
COPY key1 key2 REPLACE
Result:
(integer) 1
The integer reply of 1
indicates that the value was successfully copied.
Let’s check the value of key2
:
GET key2
Result:
"Cat"
Yes, it was successfully copied.