Skip to content

Instantly share code, notes, and snippets.

@andymccurdy
Created November 15, 2011 21:52
Show Gist options
  • Save andymccurdy/1368496 to your computer and use it in GitHub Desktop.
Save andymccurdy/1368496 to your computer and use it in GitHub Desktop.
Update
####################################################
# WARNING: This is very hacky! Use at your own risk.
#
# This assumes you have all keys in a single DB and
# want to move them all to DB 0. If you have keys
# in more than one DB, the first DB found will be
# rewritten to 0, with all others left alone.
####################################################
import shutil
def rewrite_rdb(source_file):
new_file = '%s.new' % source_file
backup_file = '%s.backup' % source_file
src = open(source_file, 'rb')
dst = open(new_file, 'wb')
# rdb header info and the SELECT statement
dst.write(src.read(10))
# write a binary 0, indicating DB:0
dst.write('\x00')
# read the byte containing the existing DB
# we don't need it.
_ = src.read(1)
# move all the rest of the data
buf = src.read(4096)
while len(buf):
dst.write(buf)
buf = src.read(4096)
src.close()
dst.close()
shutil.move(source_file, backup_file)
shutil.move(new_file, source_file)
@cr-solutions
Copy link

Hi Andy,

we currently migrate to AWS, but the problem is, that the AWS Redis Cluster do not support multiple databases.
Is it correct, that your code move all DB:x higher 0 to DB:0 without killing required keys in DB:0
Our keys in DB:0 and all other have it's own prefix.

@andymccurdy
Copy link
Author

This script changed the first database identifier in an rdb file to 0.

Backstory: When I first started using redis, I had all my keys stored in DB:1. I wrote this to move them all to DB:0. If I had keys in both DB:1 and DB:2, only they keys in DB:1 would have moved to DB:0.

Instead I would suggest using the SCAN command to iteratively fetch all keys in a database and the MOVE command to move them to DB:0.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment