Redigo: How can I get a key-value map from Redis using Golang?

1.5k Views Asked by At

Let's say I have this set of keys in my Redis:

KEY           VALUE
"agent_100"   "{name: Agent1, status:online}"
"agent_200"   "{name: Agent2, status:offline}"
"agent_300"   "{name: Agent3, status:online}"
"agent_400"   "{name: Agent4, status:offline}"

I need to return a map with all those keys and values in Golang using Redigo. The output would be something like a map[uint64]string with this key-values:

100 -> "{name: Agent1, status:online}"
200 -> "{name: Agent2, status:offline}"
300 -> "{name: Agent3, status:online}"
400 -> "{name: Agent4, status:offline}"

If I do a Scan I can get all the keys matching a pattern like agent_* and maybe then I can do a MGET with all those keys to get the values, but how I can link those keys and values in a simple way?

There's no a library function to get not only the keys that match a pattern but also the values so I can return a map with that?

I'm using redigo now but I was also looking into go-redis to see if there is a simpler way to achieve this, I'm open to consider other options.

Thanks!

1

There are 1 best solutions below

0
On

MGET preserves the order. So if you send in a list of keys, you should expect the results in the same order, with missing keys containing nil.