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

Does REDIS have a quick command that allows me to do the following

I want to set the value of key Y to the value of key X.

How do I do this from a Redis client.

I am using the standard Redis-cli client.

Basically, I'm looking for some equivalent of the following:

Y.Val() = X.Val() 
+4
source share
3 answers

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 following example uses SCRIPT LOAD to create a script and calls it with EVALSHA , passing the following arguments:

  • SHA1 returns from script load
  • a 2 for the number of keys to be transferred
  • Source key
  • Target key.

Conclusion:

 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" 

This seems like a lot compared to just GET and SET, but as soon as you load the script (and remember SHA1), you can reuse it again.

+9
source

If you do not want to load the script, 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 

Please note that key1 must already be set, otherwise you will receive the following error

Lua redis () command arguments must be strings or integers

So check as shown 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 to copy the card to another new card key

 eval "return redis.call('HMSET', KEYS[2], unpack(redis.call('HGETALL', KEYS[1])))" 2 existingMapKey newMapKey 



Another way is that when you insert time, you can insert the value into 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 problem of copying when the key is already created.

Also note that in redis there is no way for more than one key to refer to the same value object. All of these workarounds will create duplicate value objects. Therefore, if one of the values ​​is updated, it will not be reflected in the other value object.

+3
source

No, there is no quick command for this. You need the GET value of the source key, and then the SET value of the new key.

Source: http://redis.io/commands#string

+1
source

Source: https://habr.com/ru/post/1416085/


All Articles