Redis' HSET
command is used to set a field in a hash to a specific value. Common use cases include:
Let's consider we're using the popular go-redis
library.
Example 1: Set a field in a hash.
package main import ( "github.com/go-redis/redis" "fmt" ) func main() { client := redis.NewClient(&redis.Options{ Addr: "localhost:6379", }) err := client.HSet("user", "name", "John").Err() if err != nil { panic(err) } result, err := client.HGet("user", "name").Result() if err == redis.Nil { fmt.Println("No name found") } else if err != nil { panic(err) } else { fmt.Println("Name:", result) } }
In this example, we create a new client connection to a local Redis server. We then set the "name" field of the "user" hash to "John". Finally, we retrieve the "name" we just set and print it out.
HSET
. Ignoring errors can lead to hard-to-diagnose issues later on.HSET
will return an error if the field already exists in the hash. HSET
will simply overwrite any existing field with the new value.Q: Can I set multiple fields at once?
A: Yes, use the HMSet
function to set multiple field-value pairs at once.
err := client.HMSet("user", map[string]interface{}{ "name": "John", "age": 30, }).Err()
This sets both the "name" and "age" fields of the "user" hash.
Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement.