w3resource

Redis Hash: HSETNX key field value

Redis HSETNX Command

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.

Here are some common uses and scenarios for the "HSETNX" command:

  • Field Initialization: Initialize a field with a value only if it doesn't already exist.
  • Atomic Operations: Ensure atomic creation of fields without overwriting existing ones.
  • Configuration Management: Set default configuration settings that should not be overridden if they already exist.
  • Session Management: Set default attributes or data points for a session or user only if they haven't been set yet.
  • Idempotent Updates: Safely add fields to a hash without risking overwriting existing data.

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



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/redis/redis-hsetnx-key-field-value.php