Is there any quick command in REDIS which allows me to do the following
I want to set the Value of key Y equal to the value of Key X .
How do I go about doing this from the Redis Client .
I use the standard Redis-cli client .
Basically I am looking for some equivalent of the following -
Y.Val() = X.Val()
You can do this with a Lua script:
redis.call('SET', KEYS[2], redis.call('GET', KEYS[1])); return 1;
- KEYS1 is the source key
- KEYS2 is the target key
The example below uses SCRIPT LOAD to create the script and invokes it using EVALSHA passing the following arguments:
- The SHA1 returned from the script load
- a 2 for the number of keys that will be passed
- The source key
- The target key.
Output:
redis 127.0.0.1:6379> set src.key XXX
OK
redis 127.0.0.1:6379> get src.key
"XXX"
redis 127.0.0.1:6379> SCRIPT LOAD "redis.call('SET', KEYS[2], redis.call('GET', KEYS[1])); return 1;"
"1119c244463dce1ac3a19cdd4fda744e15e02cab"
redis 127.0.0.1:6379> EVALSHA 1119c244463dce1ac3a19cdd4fda744e15e02cab 2 src.key target.key
(integer) 1
redis 127.0.0.1:6379> get target.key
"XXX"
It does appear to be a lot of stuff compared to simply doing a GET and then s SET, but once you've loaded the script (and memorized the SHA1) then you can reuse it repeatedly.
If you dont want script loading then below will work as a single command.
127.0.0.1:6379> eval "return redis.call('SET', KEYS[2], redis.call('GET', KEYS[1]))" 2 key1 key2
OK
Note that key1 value should be already set else you will get the below error
Lua redis() command arguments must be strings or integers
So check like below and set
127.0.0.1:6379> GET key1
(nil)
127.0.0.1:6379> SET key1 hello
OK
Now it will work.
If you want copy map to another new map key
eval "return redis.call('HMSET', KEYS[2], unpack(redis.call('HGETALL', KEYS[1])))" 2 existingMapKey newMapKey
One more way is while inserting time itself you can insert the value to two keys using MSET.
redis> MSET key1 "Hello" key2 "Hello"
"OK"
redis> GET key1
"Hello"
redis> GET key2
"Hello"
Ofcource this will not solve the issue of copying when the key is already created.
Also note that there is no way in redis more than one key is referring the same value object. All these workaround will create duplicate value objects. So if one of the value is updated will not reflect in another value object.
No, there is no quick command to do this. You have to GET
the value of the source key, and then SET
the value of the new key.
Source: http://redis.io/commands#string