How to Update Multiple Fields in a Redis Hash

In Redis, we can update multiple fields in just the same way that we can update a single field. The HSET command allows us to set one or more fields in a hash.

The ability of the HSET command to update multiple fields was introduced in Redis 4.0.0. Prior to that, we needed to use the (now deprecated) HMSET command if we wanted to add more than one field at once.

Example

Suppose we set the following hash:

HSET customer firstname "Seth" lastname "Pitt" age 35 height 176

Result:

(integer) 4

This example already showcases HSET‘s ability to add multiple fields. If the hash already existed, it would also have updated any fields that already existed. However, in our case, all four fields were added. We can see this by the integer reply. An integer reply of 4 tells us that four fields were added.

Let’s take a look at the values in the hash:

HVALS customer

Result:

1) "Seth"
2) "Pitt"
3) "35"
4) "176"

Now let’s update a couple of those fields:

HSET customer age 36 height 177

Result:

(integer) 0

The integer reply tells us that no fields were added. However, two fields were updated. Let’s check that:

HVALS customer

Result:

1) "Seth"
2) "Pitt"
3) "36"
4) "177"

We can see that the age and height fields had their values updated 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.