SINTER, SUNION and SDIFF
Wordcraft wants a "friends in common" line on every profile and a "people you may know" list. Both are questions about two groups at once. Redis can compare sets on the server and return only the answer, instead of shipping both friend lists to your app to compare there.
The rule
INTER is "in all", UNION is "in any", DIFF is "in the first only".
The two sets:
friends:asha: ravi, meera, tomfriends:ravi: asha, meera, priya
127.0.0.1:6379> SINTER friends:asha friends:ravi
1) "meera"
127.0.0.1:6379> SUNION friends:asha friends:ravi
1) "ravi"
2) "meera"
3) "tom"
4) "asha"
5) "priya"
127.0.0.1:6379> SDIFF friends:asha friends:ravi
1) "ravi"
2) "tom"
127.0.0.1:6379> SDIFF friends:ravi friends:asha
1) "asha"
2) "priya"SINTER key [key ...]returns members found in every set. If any set is empty or missing, the answer is empty.SUNION key [key ...]returns members found in at least one set, each listed once. A missing key counts as empty.SDIFF key [key ...]returns members of the first set that appear in none of the others. Swapping the order asks a different question, as the twoSDIFFreplies show.- As with
SMEMBERS, the order of the results is not guaranteed.
Each has a STORE version that saves the result as a new set and replies with its size: SINTERSTORE common:asha:ravi friends:asha friends:ravi replies (integer) 1. SINTERCARD (Redis 7.0+) replies only with the size of the intersection, without returning the members.
Where this shows up: shared interests (SINTER), everyone subscribed to any of several topics (SUNION), and "players who started a game but have not finished one" (SDIFF started finished).
The shortcut
Draw two overlapping circles. Write shared members in the overlap and the rest on their own sides. INTER reads the overlap, UNION reads everything, DIFF reads the part of the first-named circle outside the overlap.
Fill the circles
Overlap: meera. Asha's side only: ravi, tom. Ravi's side only: asha, priya.
Drills
Answer fast — trust the rule.
a is {1, 2, 3} and b is {2, 3, 4}. What does SINTER a b return?
Same sets. What does SDIFF b a return?
Same sets. How many members does SUNION a b return?
a is {1, 2, 3} and key z does not exist. What does SINTER a z return?
What does SINTERSTORE common a b reply for the sets a {1, 2, 3} and b {2, 3, 4}?
Remember
- INTER is "in all", UNION is "in any", DIFF is "in the first only".
- Draw the circles: overlap, everything, or the first circle outside the overlap.
- SDIFF's argument order matters; STORE versions save the result and reply with its size.
