简体   繁体   中英

Go-Redis HMSet with string fields gives WRONGTYPE Operation

I'm trying to use HMSET to set a new hash containing two string fields, id and content .

I'm able to make this via redis-cli pretty easily using SET i 0 to initialize a counter for ids, then creating a new hash using HMSET test id hey content herro and getting both of these fields with HMGET test id content resulting in 1) hey 2) herro .

Unfortunately I'm not able to achieve such result with Go-Redis and in particular with HMSet .

So far I tried

var uid = "0"
err = c.Get("i").Err()
if(err != nil) {
    //If the counter is not set, set it to 0
    err := c.Set("i", "0", 0).Err()
    if(err != nil){
        panic(err)
    }
} else {
    //Else, increment it
    counter, err := c.Incr("i").Result()
    //Cast it to string
    uid = strconv.FormatInt(index, 10)
    if(err != nil){
        panic(err)
    }
    //Set new counter
    err = c.Set("i", counter, 0).Err()
    if( err!= nil ){
        panic(err)
    }
}

//Init a map[string]interface{}
var m = make(map[string]interface{})
m["id"] = uid
m["content"] = "herro"

hash, err := c.HMSet("i", m).Result()
if(err != nil){
    panic(err)
}

fmt.Println(hash)

Everything works fine but c.HMSet("i", m).Result() . I get:

WRONGTYPE Operation against a key holding the wrong kind of value

And I cannot really get why since I managed to make it work on the very same way in redis-cli .

HMSet is defined as func (c *Client) HMSet(key string, fields map[string]interface{}) *StatusCmd .

I wasn't able to find any example online using Go-Redis illustrating this use case.

What Am I doing Wrong?

You are accessing the same key "i" twice - once as a string when calling SET, and then as a hash when calling HMSET.

The error you are getting is just redis denying HMSET on a string, which is an invalid operation.

BTW the other way around will work - calling SET on any type in redis will just write a string instead of that value, so be careful.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM