How it works...

Similar to what we mentioned in the Using list data type section, we don't have to initialize an empty hash before adding fields. Redis will do this automatically with HSET and HMSET. Similarly, Redis will do the clean-up work when a hash is empty.

By default, HSET and HMSET will overwrite any existing fields. The HSETNX command, which sets the value of a field only if the field does not exist, can be used to prevent the default overwriting behavior of HSET:

127.0.0.1:6379> HSETNX "Kyoto Ramen" "phone" "555-555-0001" 
(integer) 0 
127.0.0.1:6379> HGET "Kyoto Ramen" "phone" 
"555-123-6543"  

HMGET and HGET will return (nil) for any non-existent key or field:

127.0.0.1:6379> HMGET "Kyoto Ramen" "rating" "hours" 1) "4.9" 2) (nil) ...

Get Redis 4.x Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.