HSETNX command in Redis is used to set a field in a hash to a value, only if the field does not already exist. If the field exists, nothing is done. This is particularly useful when you want to ensure uniqueness of fields in a hash, like username in a user profile storage system.
Let's look at an example in Golang using the
In this example, we create a new client connected to a local Redis instance and then use
HSetNX to set the
username field of the hash
john only if it does not exist. Then, we retrieve and print the value for verification.
HSETNXwhen you need to guarantee uniqueness of a field within a hash.
HSetNX. Ignoring this might lead to silent failures where the program behaves unexpectedly without any signs of errors.
One common mistake is to assume that
HSetNX will update the value if the field already exists. This is not true, it only sets the field if it doesn't exist. Use
HSET instead if you want to always set (or overwrite) the value.
Q: What happens if the hash does not exist? A: If the hash does not exist, it is created and the specified field is set.
Q: What is the return value of HSETNX?
A: The return value of the
HSETNX command is a boolean:
true if the field was set, and
false if it was not set (because it already existed).