Redis HSET Command

In Redis, the HSET command enables us to set one or more fields in a hash. It sets the field/s at the specified key to the value/s we provide.

If the key doesn’t exist, it’s created with the specified hash value. If the field already exists, it is overwritten with the new value.

Syntax

The syntax goes like this:

HSET key field value [field value ...]

This shows us that we can set multiple fields in the key. This functionality was added in Redis 4.0.0. Prior to that, we could only set one field, and the HMSET command was used for setting multiple fields. The HMSET command has been deprecated since Redis 4.0.0. due to the HSET command providing the same functionality.

Example

Here’s a basic example to demonstrate:

HSET customer firstname "Rob" lastname "Banks"

Result:

(integer) 2

In this case, the key didn’t already exist and so it was created with the specified fields and their respective values. The HSET operation was successful and we got an integer reply of 2, which is how many fields were added. To be clear, this is not necessarily how many fields were set, it’s how many fields that were added.

Let’s use HGETALL to get all the fields and values in our hash:

HGETALL customer

Result:

1) "firstname"
2) "Rob"
3) "lastname"
4) "Banks"

The hash was set as expected.

When the Key Already Exists

If both the key and the specified field already exists, the field is updated to the new value.

If the key exists but the field doesn’t, the field is added to the key with the specified value.

HSET customer lastname "Burr" age "30"

Result:

(integer) 1

Two fields were affected – one was updated and one was added. In this case we get an integer reply of 1, which is how many fields that were added.

Let’s take another look at the hash:

HGETALL customer

Result:

1) "firstname"
2) "Rob"
3) "lastname"
4) "Burr"
5) "age"
6) "30"

We can see that the changes were effected as specified.

Trying to Set a non-Hash Key

If the key exists, but it’s not a hash, we get an error:

HSET color rgb "0000FF" name "Blue"

Result:

(error) WRONGTYPE Operation against a key holding the wrong kind of value

In this case, the color key is actually a string. So Redis prevented it from being updated and returned this error message.

Passing the Wrong Number of Arguments

Passing the wrong number of arguments results in an error:

HSET customer

Result:

(error) ERR wrong number of arguments for 'hset' command