How to write the below in Redis
"Create a sorted set myset1 with the following values ( 1, ‘a’, 2, ‘b’, 3 , ‘c’).Create a sorted set myset 2 with the following values (4, ‘b’, 1, ‘c’, 0, ‘d’).Find the intersection of myset1 and myset2 : – Write a command to find the intersection of myset1 and myset2 and store the intersection in out- Write a command to see the resulting intersection output Sorted set "out" : Find the union of myset1 and myset2 – Write a command to take the union of myset1 and myset2 and store the output in unout – Write a command to see the resulting intersection output Sorted set "unout" "
I wrote the code like below and it says 80% correct.
127.0.0.1:6379> zadd myset1 0 1 0 a 0 2 0 b 0 3 0 c (integer) 6 127.0.0.1:6379> zadd myset2 0 4 0 b 0 1 0 c 0 0 0 d (integer) 6 127.0.0.1:6379> zinterstore out 2 myset1 myset2 (integer) 3 127.0.0.1:6379> zrange out 0 -1 1) "1" 2) "b" 3) "c" 127.0.0.1:6379> zunionstore unout 2 myset1 myset2 (integer) 9 127.0.0.1:6379> zrange unout 0 -1 1) "0" 2) "1" 3) "2" 4) "3" 5) "4" 6) "a" 7) "b" 8) "c" 9) "d" 127.0.0.1:6379>
2
Answers
You can use
ZINTERSTORE
andZUNIONSTORE
commands to computer intersection and union of intersection of sorted sets.ZINTERSTORE
ZINTERSTORE destination numkeys key [key …] [WEIGHTS weight [weight …]] [AGGREGATE SUM|MIN|MAX]
ZUNIONSTORE
ZUNIONSTORE destination numkeys key [key …] [WEIGHTS weight [weight …]] [AGGREGATE SUM|MIN|MAX]
Edit:
It’s not accepting since you’re adding score as key as well
Yout
ZADD
commands should beTry this