The 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 go-redis
package:
package main import ( "fmt" "github.com/go-redis/redis/v8" "context" ) var ctx = context.Background() func main() { rdb := redis.NewClient(&redis.Options{ Addr: "localhost:6379", Password: "", DB: 0, }) err := rdb.HSetNX(ctx, "user:1000", "username", "john").Err() if err != nil { panic(err) } val := rdb.HGet(ctx, "user:1000", "username").Val() fmt.Println("username:", val) }
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 user:1000
to john
only if it does not exist. Then, we retrieve and print the value for verification.
HSETNX
when 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).
Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement.