'Inserting an empty map into Redis using HSET fails in Golang
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?
Solution 1:[1]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
