How to Rename Fields in Hash for Multiple Keys in Redis
Let’s say you want you started out naming fields with under_scores, and another team member used camelCase. Now your redis hashes are a mess, and you’d rather stick to one convention. You need a way to rename fields across all hashes.
Redis does not have a way to rename fields within a hash. But more importantly, there is no way to do it for all the hashes you have created.
Fortunately, a little command line magic is all that is needed to fix the mess.
This command will find keys matching the pattern users:*, and then rename fields
- creation_date to creationDate
- posttypeid to postTypeId
- view_count to viewCount
- … and so on
The Missing “hrename” Command
Redis does not have a hrename command, so we first write one in lua script. This command will rename fields within a single hash.
evalsha <script-sha1-identifier> 1 <key> <old-field-1> <new-field-1>...
You will need to first load the script. The command
cat hrename.lua | redis-cli -x script load loads the script and returns a SHA1 identifier. You can use this identifier whenever you want to invoke the script.
Renaming Fields in Multiple Hashes
Now that we have a command to fix a single hash, we need to run it in a loop for all the hashes that match a pattern. The script
hash_bulk_rename_fields.sh does just that.
- First, we use
redis-cli --scan --pattern <pattern>to get a list of keys, one key per line.
- Next, we pass the keys through
grep. Redis scan command does not accept regular expressions, so we do basic filtering with scan, and then provide a better regular expression via grep.
- We then run an awk script for each key. This awk script is a little complex, so we will break it down
- The awk script has a command template
evalsha <sha1> 1 __key__ <old field name> <new field name>... This is the command that will run for all keys.
- For each matching key, the awk command replaces
__key__with the actual key
- Next, we convert the string command to redis protocol format. This is the raw format that redis understands.
- Finally, we pipe the raw commands to redis-cli using the –pipe flag. This is the most efficient way to send bulk commands to redis.
Customizing this Script
- You can change
--patternand the grep command to select the keys that are of type hash
- You can customize
cmd_templateto include the fields you want to rename
- 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.