timpone
timpone

Reputation: 19969

Way to get counts when doing sunion in Redis

I'm evaluating using Redis and but one use case is outstanding. I'd like to use SUNION but also get back the counts. Like currently for SUNION from their docs http://redis.io/commands/sunion:

key1 = {a,b,c,d}
key2 = {c}
key3 = {a,c,e}
SUNION key1 key2 key3 = {a,b,c,d,e}

but would like:

SOTHERUNION key1 key2 key3 = {a:2,b:1,c:3,d:1,e:1}

and ideally sorted like:

SOTHERUNION key1 key2 key3 = {c:3, a:2,b:1,d:1,e:1}

Is this possible (esp in a highly performant way)? We do this in MySQL and could potentially be problematic.

Upvotes: 1

Views: 361

Answers (1)

Itamar Haber
Itamar Haber

Reputation: 50102

SUNION will not help you here but ZUNIONSTORE is what you're looking for. Despite its name, it also works on regular sets (giving members the score of 1 by default) and coupled with the AGGREGATE SUM clause, it will yield the requested result:

127.0.0.1:6379> sadd key1 a b c d
(integer) 4
127.0.0.1:6379> sadd key2 c
(integer) 1
127.0.0.1:6379> sadd key3 a c e
(integer) 3
127.0.0.1:6379> zunionstore result 3 key1 key2 key3 aggregate sum
(integer) 5
127.0.0.1:6379> zrevrangebyscore result +inf -inf
1) "c"
2) "a"
3) "e"
4) "d"
5) "b"
127.0.0.1:6379> zscore result c
"3"
127.0.0.1:6379> zscore result a
"2"
127.0.0.1:6379> zscore result e
"1"
127.0.0.1:6379> zscore result d
"1"
127.0.0.1:6379> zscore result b
"1"

Upvotes: 4

Related Questions