Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redis : How to set one key equal to the value of another key?

Tags:

database

redis

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()
like image 439
geeky_monster Avatar asked Jun 05 '12 03:06

geeky_monster


Video Answer


2 Answers

You can do this with a Lua script:

redis.call('SET', KEYS[2], redis.call('GET', KEYS[1])); return 1;
  1. KEYS1 is the source key
  2. KEYS2 is the target key

The example below uses SCRIPT LOAD to create the script and invokes it using EVALSHA passing the following arguments:

  1. The SHA1 returned from the script load
  2. a 2 for the number of keys that will be passed
  3. The source key
  4. 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.

like image 100
Nicholas Avatar answered Sep 23 '22 16:09

Nicholas


Since 6.2.0 you have a COPY command :

https://redis.io/commands/copy

like image 29
Jérôme Lepeltier Avatar answered Sep 23 '22 16:09

Jérôme Lepeltier