4 Ways to Insert a Field in a Redis Hash

I decided to compile a list of commands that can insert a new field into a Redis hash. Here are four options for inserting a new field into a Redis hash.

The HSET Command

The HSET command is probably the most obvious one. It allows us to set fields in a Redis hash. But more importantly for this article, if the field doesn’t already exist, it inserts the field and sets it to the specified value.

 HSET pet name "Wag"

Result:

(integer) 1

We can see by the integer reply that one field was inserted.

In my case the key didn’t exist, and so it was created and the field was added as specified.

Let’s use HGETALL to check the contents of the hash:

HGETALL pet

Result:

1) "name"
2) "Wag"

The field has been inserted as specified.

Be aware that if the field already exists in the hash, it is overwritten with the new value. If you don’t want to overwrite any existing fields, see the HSETNX command below.

The HSETNX Command

The HSETNX command is similar to HSET, except that it only adds the field if it doesn’t already exist. This can be handy if you don’t want to accidentally overwrite another field. With HSET, if the field already exists, it’s overwritten with the new value. However, with HSETNX, if the field already exists it is not updated.

 HSETNX pet color "Brown"

Result:

(integer) 1

In this case the field didn’t already exist and the new field was added.

Here’s what happens when the field already exists:

 HSETNX pet color "Brown"

Result:

(integer) 0

The HINCRBY Command

The HINCRBY command increments the number stored at a field by the specified amount. If the field doesn’t exist, it’s created, set to zero, and incremented by the specified amount.

This command is limited to 64 bit signed integers, therefore, we would only use it when we want the field to contain an integer.

HINCRBY pet age 3

Result:

(integer) 3

The integer reply tells us the value of the field after it has been incremented.

Let’s check the contents of the hash now:

HGETALL pet

Result:

1) "name"
2) "Wag"
3) "color"
4) "Brown"
5) "age"
6) "3"

The HINCRBYFLOAT Command

The HINCRBYFLOAT command is similar to HINCRBY but it is intended to be used on floating point numbers. As with the other commands listed above, if the field doesn’t already exist, it’s inserted.

HINCRBYFLOAT pet height 7.85

Result:

"7.85"

The bulk string reply tells us the value of the field after it has been incremented. In our case, the field was inserted first, set to zero, then incremented by the specified amount.

Let’s check the contents of the hash now:

HGETALL pet

Result:

1) "name"
2) "Wag"
3) "color"
4) "Brown"
5) "age"
6) "3"
7) "height"
8) "7.85"