英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论