How to Add Multiple Fields to a Redis Hash

Ever since Redis 4.0.0, the HSET command has allowed us to add (and update) multiple fields to a hash.

Prior to Redis 4.0.0, we needed to use the (now deprecated) HMSET command to add more than one field at once.

Example

Here’s an example of adding multiple fields to a Redis hash:

HSET customer firstname "Seth" lastname "Pitt"

Result:

(integer) 2

Here, I added two fields to the hash stored at the customer key. In this case the key didn’t exist, and so it was created and the two fields added. The integer reply of 2 tells us that two fields were added.

Let’s take a look at the hash:

HGETALL customer

Result:

1) "firstname"
2) "Seth"
3) "lastname"
4) "Pitt"

The two fields were added as specified.

Let’s add some more fields:

HSET customer height 170 weight 120

Result:

(integer) 2

The integer reply tells us that two fields were added.

Let’s take another look at the hash:

HGETALL customer

Result:

1) "firstname"
2) "Seth"
3) "lastname"
4) "Pitt"
5) "height"
6) "170"
7) "weight"
8) "120"

We can see that the two fields were added as specified.

About the HMSET Command

You may be aware of the HMSET command that was designed specifically for setting multiple fields in a Redis hash. However, this command was deprecated in Redis 4.0.0 when the HSET command was modified to allow multiple fields to be set in one go.

Therefore, it’s recommended that you use HSET instead of HMSET.

About the HSETNX Command

The HSETNX command allows us to set a field only if the field doesn’t already exist. You might assume that this command also allows us to set/insert multiple fields at once. However, at the time of writing, it only allows us to set/add one field at a time.