在Golang中使用HSET将空映射插入Redis失败。

huangapple go评论88阅读模式
英文:

Inserting an empty map into Redis using HSET fails in Golang

问题

我有一些代码,用于使用HSET命令将地图插入到Redis中:

prefix := "accounts|asdfas"
data := make(map[string]string)
if _, err := conn.Do("HSET", redis.Args{}.Add(prefix).AddFlat(data)...); err != nil {
	return err
}

如果data中有值,那么这段代码将正常工作,但如果data为空,则会出现以下错误:

ERR wrong number of arguments for 'hset' command

看起来这是AddFlat函数将地图转换为交错的键和它们关联值列表的结果。当地图为空时,这是无法工作的,这是有道理的,但我不确定如何处理它。我不想向地图中添加空值,但这是我能想到的唯一办法。有没有一种更符合Redis应该处理的方式来处理这个问题?

英文:

I have some code to insert a map into Redis using the HSET command:

prefix := "accounts|asdfas"
data := make(map[string]string)
if _, err := conn.Do("HSET", redis.Args{}.Add(prefix).AddFlat(data)...); err != nil {
	return err
}

If data has values in it then this will work but if data is empty then it will issue the following error:

> ERR wrong number of arguments for 'hset' command

It seems that this is the result of the AddFlat function converting the map to an interleaved list of keys and their associated values. It makes sense that this wouldn't work when the map is empty but I'm not sure how to do deal with it. I'd rather not add an empty value to map but that's about all I can think to do. Is there a way to handle this that's more inline with how things are supposed to be done on Redis?

答案1

得分: 1

作为一个经验法则,Redis 不允许并且从不保留空的数据结构(有一个例外情况)。

以下是一个示例:

> HSET members foo bar
(integer) 1

> EXISTS members
(integer) 1

> HDEL members foo
(integer) 1

> EXISTS members
(integer) 0

因此,如果你想保留你的数据结构,你至少要在其中添加一个成员。你可以在哈希表中添加一个虚拟项,并在应用逻辑中忽略它,但这可能与其他数据结构(如列表)不兼容。

英文:

As a general rule of thumb, Redis doesn't allow and never keeps an empty data structure around (there is one exception to this tho).

Here's an example:

> HSET members foo bar
(integer) 1

> EXISTS members
(integer) 1

> HDEL members foo
(integer) 1

> EXISTS members
(integer) 0

As a result if you want to keep your data structures around, you have to at least have one member inside them. You can add a dummy item inside the Hash
and ignore it in your application logic but it may not work well with other data structures like List.

huangapple
  • 本文由 发表于 2022年3月15日 16:57:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/71479411.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定