Learnitweb

Redis Set Operations: Intersection, Union, and Difference

Redis sets are unordered collections of unique elements. One of the powerful features of sets is the ability to perform set operations such as intersection, union, and difference, which can be useful for real-world scenarios like filtering candidates based on skills.


Example Scenario

Imagine an application similar to LinkedIn or Dice:

  • Candidates upload their resumes and list their skills.
  • Hiring managers want candidates with specific skill sets.

We can model the candidates with Redis sets:

  • skill:java → candidates who know Java.
  • skill:javascript → candidates who know JavaScript.
  • skill:python → candidates who know Python, etc.

1. Intersection (SINTER)

The intersection finds elements that exist in all sets.

Use case: Find candidates who know both Java and JavaScript.

SINTER skill:java skill:javascript
  • Returns candidates who are present in both sets.
  • Example output: 4 → candidate 4 knows both Java and JavaScript.

This is useful for hiring managers looking for candidates with all required skills.


2. Union (SUNION)

The union finds elements that exist in any of the sets.

Use case: Find candidates who know either Java or JavaScript (or both).

SUNION skill:java skill:javascript
  • Returns candidates who are in either set.
  • Example output: 1, 2, 3, 4 → all candidates who know at least one of the skills.

Union is useful when the requirement is flexible: candidates can know any one of multiple skills.


3. Difference (SDIFF)

The difference finds elements that are in the first set but not in the second set.

Use case: Exclude candidates who meet some undesirable criteria.

SDIFF skill:java skill:criminal_records
  • Returns candidates who know Java but do not have a criminal record.
  • Example output: 1, 2, 3 → removes candidates present in skill:criminal_records.

Difference is useful for filtering out unwanted candidates or items from a set.


4. Storing the Result in a New Set

Redis allows you to store the result of intersection, union, or difference in a new set for further queries:

SINTERSTORE skill:java_and_javascript skill:java skill:javascript
  • skill:java_and_javascript now contains all candidates who know both Java and JavaScript.
  • You can now query this new set:
SCARD skill:java_and_javascript   # Count of candidates
SMEMBERS skill:java_and_javascript # List candidates

This avoids recomputing intersections multiple times.


Summary of Set Commands

OperationCommand ExampleDescription
IntersectionSINTER key1 key2Elements in all sets
UnionSUNION key1 key2Elements in any set
DifferenceSDIFF key1 key2Elements in first set not in others
Store ResultSINTERSTORE dest key1 key2Save result in a new set