Copy all keys from one db to another in redis

Copies all keys from database number 0 to database number 1 on localhost.

redis-cli --scan | xargs redis-cli migrate localhost 6379 '' 1 0 copy keys

If you use the same server/port you will get a timeout error but the keys seem to copy successfully anyway. GitHub Redis issue #1903


If you can't use MIGRATE COPY because of your redis version (2.6) 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.


redis-cli -a $source_password -p $source_port -h $source_ip keys /*| while read key; 
do echo "Copying $key"; 
redis-cli --raw -a $source_password -h $source_ip -p $source_port -n $dbname DUMP "$key"| head -c -1| redis-cli -x -a $destination_password -h $destination_IP -p $destination_port RESTORE "$key" 0;

Tags:

Redis