Skip to content

Instantly share code, notes, and snippets.

@fabware
Forked from josiahcarlson/copy_redis.py
Created October 21, 2010 12:55
Show Gist options
  • Save fabware/638436 to your computer and use it in GitHub Desktop.
Save fabware/638436 to your computer and use it in GitHub Desktop.
'''
Copyright 2010 Josiah Carlson
Released into the public domain
copy_redis.py
A convenient utility function for copying data from one redis server to
another.
Requires http://github.com/andymccurdy/redis-py .
'''
import time
def copy_redis(source_redis, dest_redis, dbs):
if isinstance(dbs, (int, long)):
dbs = xrange(dbs)
for db in dbs:
source_redis.select(db)
dest_redis.select(db)
# depending on your use-case, you may want to comment the next line
dest_redis.flushdb()
keys = source_redis.keys()
lk = len(keys)
t = time.time()
for i, key in enumerate(keys):
if i and not i % 10000:
print "%i: %i / %i | %.1f" %(db, i, lk, time.time()-t)
type = source_redis.type(key)
if type == 'set':
d = dest_redis.pipeline()
for v in source_redis.smembers(key):
d.sadd(key, v)
_ = d.execute()
elif type == 'hash':
dest_redis.hmset(key, source_redis.hgetall(key))
elif type == 'string':
dest_redis.set(key, source_redis.get(key))
elif type == 'zset':
d = dest_redis.pipeline()
for sk, v in source_redis.zrange(key, 0, -1, withscores=True):
d.zadd(key, sk, v)
_ = d.execute()
elif type == 'list':
d = dest_redis.pipeline()
for v in source_redis.lrange(key, 0, -1):
d.rpush(key, v)
_ = d.execute()
elif type == 'none':
# we got a key in a strange state, skip it
continue
else:
print "key %s has unknown type %s"%(key, type)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment