How to Rename Multiple Keys in Redis

Redis does not offer a command to bulk rename keys in redis. But it is easy enough to create a script using redis-cli and some command line tools.

This command will rename keys matching users:* to customers*:

How does the Script Work?

  1. First, we use redis-cli --scan --pattern <pattern> to get a list of keys that should be renamed. Since we are using the scan command, this does not block redis server.
  2. Next, we use awk to do string substition and generate a new name. This is the gsub(/users/,"customers", new_key) in the bash command
  3. Next, we use generate our command rename <old key> <new key>, but to make it efficient, we generate it in the redis protocol format.
  4. Finally, we pipe the redis protocol to redis-cli with the --pipe option. This is the most efficient way to send a stream of commands to redis server.

Customizing this Script

  1. If your redis server is not on localhost, you will have to provide the host, port and password twice in the command, basically whenever you call redis-cli.
  2. You will have to substitute the scan pattern and the gsub call to meet your needs.

See Also