Search code examples
rediszset

Merge Redis set members values using a pattern


I have a simple zset named pets:

redis-cli zadd pets 1 cat1
redis-cli zadd pets 1 cat2
redis-cli zadd pets 1 cat3

redis-cli zadd pets 1 rat1
redis-cli zadd pets 1 rat2

The value is always 1. Now the set state is redis-cli zrange pets 0 -1 withscores:

 1) "cat1"
 2) "1"
 3) "cat2"
 4) "1"
 5) "cat3"
 6) "1"
 7) "rat2"
 8) "1"
 9) "rat1"
10) "1"

Is there a way to merge set members based on a pattern? I want to sum all the members with the name starting with a prefix, in my case the pet type, so as to end up with the following:

1) "cat"
2) "3"
3) "rat"
4) "2"

I have tried zinterstore and zunionstore but they enforce having the same name for members of the sets.


Solution

  • Nope, there isn't a built-in Redis gimmick for that, but you could majik it with a Lua script (see the EVAL command).

    That said, if what you need is count of pet by prefix, you should consider an alternative data model that can serve that.