How do you find the intersection, union, and difference between two or more Redis sets?
Short answer
You use SINTER to find items that exist in every specified set, SUNION to find items that exist in at least one of the specified sets, and SDIFF to find items that exist in the first specified set but not in any of the others, giving you powerful built-in set algebra operations…
Advertisement
AModel answer
You use SINTER to find items that exist in every specified set, SUNION to find items that exist in at least one of the specified sets, and SDIFF to find items that exist in the first specified set but not in any of the others, giving you powerful built-in set algebra operations directly within Redis.
Example
SADD set1 'a' 'b' 'c' SADD set2 'b' 'c' 'd' SINTER set1 set2 -- returns 'b', 'c' SUNION set1 set2 -- returns 'a', 'b', 'c', 'd' SDIFF set1 set2 -- returns 'a'
Real-world example
A social networking feature finds mutual friends between two users using SINTER on their respective friend sets, quickly identifying shared connections without needing to write custom comparison logic.
Likely follow-ups
- Are there store variants of these commands that save the result directly into a new set?
- How does the performance of these operations scale with the size of the sets involved?
Related topics