Skip to content

Instantly share code, notes, and snippets.

@allan-simon
Created April 9, 2016 14:11
Show Gist options
  • Save allan-simon/fe0c6bd3c7c7fd478ed6ea3a96bc3726 to your computer and use it in GitHub Desktop.
Save allan-simon/fe0c6bd3c7c7fd478ed6ea3a96bc3726 to your computer and use it in GitHub Desktop.
"""
Copies all keys from the source Redis host to the destination Redis host.
Useful to migrate Redis instances where commands like SLAVEOF and MIGRATE are
restricted (e.g. on Amazon ElastiCache).
The script scans through the keyspace of the given database number and uses
a pipeline of DUMP and RESTORE commands to migrate the keys.
Requires Redis 2.8.0 or higher.
Python requirements:
redis==2.10.3
"""
import os
import redis
from redis.exceptions import ResponseError
def migrate():
source = redis.Redis(os.getenv('REDIS_HOST'))
size = source.dbsize()
if size == 0:
print 'No keys found.'
return
COUNT = 2000 # scan size
non_existing = 0
already_existing = 0
cursor = 0
while True:
cursor, keys = source.scan(cursor, count=COUNT)
pipeline = source.pipeline()
for key in keys:
pipeline.pttl(key)
pipeline.dump(key)
result = pipeline.execute()
for key, ttl, data in zip(keys, result[::2], result[1::2]):
if ttl is None:
ttl = 0
if data != None:
print('%s %s' % (key, data.encode('base64').replace('\n', '')))
else:
non_existing += 1
if cursor == 0:
break
if __name__ == '__main__':
migrate()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment