Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy all keys from one db to another in redis

Tags:

redis

Instade of move I want to copy all my keys from a particular db to another. Is it possible in redis if yes than how ?

like image 463
Subo Avatar asked Apr 22 '14 14:04

Subo


People also ask

How can you move a key to another database using Redis key commands?

You can move an individual key to another database in your Redis instance with the move command. move takes the name of a key and the database where you want to move the key as arguments. For example, to move the key key_1 to database 8 , you would run the following: move key_1 8.

How do I get Redis all keys?

To list the keys in the Redis data store, use the KEYS command followed by a specific pattern. Redis will search the keys for all the keys matching the specified pattern. In our example, we can use an asterisk (*) to match all the keys in the data store to get all the keys.

Can Redis have duplicate keys?

You can use the DUMP and RESTORE commands to duplicate the key: use the DUMP command to serialize the value of a key. use the RESTORE command to restore the serialized value to another key.


1 Answers

If you can't use MIGRATE COPY because of your redis version you might want to copy each key separately which takes longer but doesn't require you to login to the machines themselves and allows you to move data from one database to another. Here's how I copy all keys from one database to another (but without preserving ttls)

#set connection data accordingly source_host=localhost source_port=6379 source_db=0 target_host=localhost target_port=6379 target_db=1  #copy all keys without preserving ttl! redis-cli -h $source_host -p $source_port -n $source_db keys \* | while read key; do     echo "Copying $key"     redis-cli --raw -h $source_host -p $source_port -n $source_db DUMP "$key" \         | head -c -1 \         | redis-cli -x -h $target_host -p $target_port -n $target_db RESTORE "$key" 0 done 

Keys are not going to be overwritten, in order to do that, delete those keys before copying or simply flush the whole target database before starting.

like image 171
estani Avatar answered Sep 28 '22 08:09

estani