Redis HSETNX Command

In Redis, the HSETNX command enables us to set a field in a hash, but only if the field doesn’t already exist. It sets the field at the specified key to the value we provide.

If the key doesn’t exist, it’s created with the specified hash value. If the field already exists, nothing is set (i.e. the command has no effect).

Syntax

The syntax goes like this:

HSETNX key field value

Example

Here’s a basic example to demonstrate:

HSETNX customer firstname "Rob"

Result:

(integer) 1

In this case, the field didn’t already exist and so it was created with the specified field and the specified value.

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

HGETALL customer

Result:

1) "firstname"
2) "Rob"

We can see that the hash was set as expected.

When the Key Already Exists

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

HSETNX customer lastname "Banks"

Result:

(integer) 1

But if the field already exists, no operation takes place:

HSETNX customer lastname "Burr"

Result:

(integer) 0

We can verify this by looking at the hash’s contents:

HGETALL customer

Result:

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

The lastname field still holds Banks, which is the first value we set above.

Trying to Set a non-Hash Key

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

HSETNX color rgb "0000FF"

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:

HSETNX customer firstname "Rob" lastname "Banks"

Result:

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