RedisInsight is the successor to RDBTools! RDBTools will reach EOL on 31st December 2019

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 does just that.

  1. First, we use redis-cli --scan --pattern <pattern> to get a list of keys, one key per line.
  2. 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.
  3. We then run an awk script for each key. This awk script is a little complex, so we will break it down
  4. 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.
  5. For each matching key, the awk command replaces __key__ with the actual key
  6. Next, we convert the string command to redis protocol format. This is the raw format that redis understands.
  7. 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

  1. You can change --pattern and the grep command to select the keys that are of type hash
  2. You can customize cmd_template to include the fields you want to rename
  3. 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.

See Also