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?
- 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.
- 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
- Next, we use generate our command
rename <old key> <new key>, but to make it efficient, we generate it in the redis protocol format.
- Finally, we pipe the redis protocol to redis-cli with the
--pipeoption. This is the most efficient way to send a stream of commands to redis server.
Customizing this Script
- 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.
- You will have to substitute the scan pattern and the gsub call to meet your needs.