w3resource

Redis Hash: HSETNX key field value

HSETNX key field value

Redis HSETNX command is used to set the field in the hash stored at the key to value, only if the field does not yet exist. If the key does not exist, a new key holding a hash is created. If the field already exists, this operation has no effect.

Syntax:

HSETNX KEY_NAME FIELD VALUE    

Available since

2.0.0.

Return Value

Integer reply

Return Value Type

Integer

  • 1 if the field is a new field in the hash and value was set.
  • 0 if the field already exists in the hash and no operation was performed.

Example: Redis HSETNX

127.0.0.1:6379> HSETNX langhash lan1 "example"
(integer) 1
127.0.0.1:6379> HSETNX langhash lan2 "Tutorial"
(integer) 1
127.0.0.1:6379> HSETNX langhash lan1 "PHP"
(integer) 0
127.0.0.1:6379> HSETNX langhash lan2 "JavaScript"
(integer) 0
127.0.0.1:6379> HGET langhash lan1
"example"
127.0.0.1:6379> HGET langhash lan2
"Tutorial"

Example: Redis HSETNX another example

127.0.0.1:6379> HSETNX user-y email [email protected]
(integer) 0
127.0.0.1:6379> HSETNX user-v email [email protected]
(integer) 1
127.0.0.1:6379> HGET user-y email
"[email protected]"
127.0.0.1:6379> HGET user-v email
"[email protected]"

Previous: HSET
Next: HVALS



Follow us on Facebook and Twitter for latest update.