duangang4001 2017-05-02 20:40
浏览 530
已采纳

带字符串字段的Go-Redis HMSet提供WRONGTYPE操作

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?

  • 写回答

1条回答 默认 最新

  • dongsao8279 2017-05-02 20:47
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 一道python难题
  • ¥15 用matlab 设计一个不动点迭代法求解非线性方程组的代码
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试
  • ¥20 问题请教!vue项目关于Nginx配置nonce安全策略的问题
  • ¥15 教务系统账号被盗号如何追溯设备
  • ¥20 delta降尺度方法,未来数据怎么降尺度