Learn Redis Β· 5/15

Uniqueness and Math: Working with Sets

5 min read

Uniqueness and Math: Working with Sets πŸ”’

Welcome to the world of Redis Sets! Imagine you're throwing a party and want to keep a list of everyone who RSVPs. You wouldn't want to count the same person twice if they accidentally RSVP more than once, right? Sets are the perfect tool for this job. They are collections of unique strings, unordered, and incredibly efficient for certain tasks.

1. Introduction to Sets: Ensuring Unique Elements πŸ›‘οΈ

The Problem: You need to store a collection of items, but you must ensure that there are absolutely no duplicates. For instance, think about a list of unique visitors to a website or the tags associated with a blog post.

The Solution: Redis Sets to the rescue! A Set in Redis is an unordered collection of unique strings. The "unique" part is the magic here. No matter how many times you try to add the same element to a set, it will only be stored once.

Think of it like a club with a strict "one-of-a-kind" membership policy. You can try to give your friend a second membership card, but the bouncer (Redis) will just chuckle and say, "They're already in, pal."

Under the hood, Redis uses a data structure called a hash table to store sets. This allows for incredibly fast additions, removals, and checks for membership, regardless of how many elements are in the set.

2. Adding, Removing, and Checking Members: SADD, SREM, SISMEMBER βž•βž–β“

Let's get our hands dirty with some of the most common and essential Set commands.

Adding Members with SADD

To add one or more members to a set, you use the SADD command. If the key doesn't exist, Redis will create it for you.

Syntax: SADD key member [member ...]

Example:

Let's create a set of attendees for our epic developer conference, "CodeChella."

shell
SADD codechella_attendees "Alice" "Bob" "Charlie"
# (integer) 3

Now, what happens if "Alice" tries to RSVP again?

shell
SADD codechella_attendees "Alice" "David"
# (integer) 1

Notice that Redis returns 1, indicating that only one new element ("David") was added. "Alice" was already a member, so she wasn't added again.

Checking for Membership with SISMEMBER

To check if a specific person is on our attendee list, we can use the SISMEMBER command.

Syntax: SISMEMBER key member

Example:

shell
SISMEMBER codechella_attendees "Bob"
# (integer) 1

Redis returns 1 which means "Yes, Bob is in the set."

shell
SISMEMBER codechella_attendees "Eve"
# (integer) 0

And 0 means "Nope, Eve is not in the set."

Removing Members with SREM

Oops, it turns out Charlie can't make it. Let's remove him from the list using SREM.

Syntax: SREM key member [member ...]

Example:

shell
SREM codechella_attendees "Charlie"
# (integer) 1

Redis returns 1 to let us know that one member was successfully removed.

Getting All Members with SMEMBERS

If you want to see everyone who's coming to CodeChella, you can use SMEMBERS.

Syntax: SMEMBERS key

Example:

shell
SMEMBERS codechella_attendees
# 1) "Alice"
# 2) "Bob"
# 3) "David"

Remember, sets are unordered, so the order in which the members are returned is not guaranteed.

3. Set Mathematics: Intersections, Unions, and Differences πŸ“

This is where the real power of Redis Sets shines. You can perform mathematical operations on sets to derive meaningful data.

Imagine we have another developer conference, "DevFest."

shell
SADD devfest_attendees "David" "Frank" "Grace"

Unions with SUNION

The union of two or more sets contains all the elements that are in any of the sets. It's like combining the guest lists of both conferences.

Syntax: SUNION key [key ...]

Example:

shell
SUNION codechella_attendees devfest_attendees
# 1) "Alice"
# 2) "Bob"
# 3) "David"
# 4) "Frank"
# 5) "Grace"

Intersections with SINTER

The intersection of two or more sets contains only the elements that are present in all of the sets. This is great for finding out who is attending both conferences.

Syntax: SINTER key [key ...]

Example:

shell
SINTER codechella_attendees devfest_attendees
# 1) "David"

It looks like "David" is a very busy developer!

Differences with SDIFF

The difference between two sets contains the elements that are in the first set but not in the second. Let's find out who is going to CodeChella but not DevFest.

Syntax: SDIFF key [key ...]

Example:

shell
SDIFF codechella_attendees devfest_attendees
# 1) "Alice"
# 2) "Bob"

4. Practical Use Cases: Tagging Systems and Social Graphs 🏷️πŸ‘₯

Now, let's see how these concepts are applied in the real world.

Tagging Systems

Imagine you have a blog and you want to tag your posts. You can use a Redis Set for each tag to store the IDs of the posts associated with that tag.

For example, a post with ID 123 is tagged with "redis" and "database".

shell
SADD tag:redis 123
SADD tag:database 123

A post with ID 456 is tagged with "redis" and "nosql".

shell
SADD tag:redis 456
SADD tag:nosql 456

Now, if you want to find all posts tagged with "redis", you can simply do:

shell
SMEMBERS tag:redis
# 1) "123"
# 2) "456"

To find posts tagged with both "redis" AND "database", you'd use an intersection:

shell
SINTER tag:redis tag:database
# 1) "123"

Social Graphs: Mutual Friends

Redis Sets are fantastic for managing relationships in social networks. Let's say you have a set for each user's friends.

  • Alice's friends: friends:alice
  • Bob's friends: friends:bob

To find their mutual friends, you would perform an intersection of their friend sets.

shell
SINTER friends:alice friends:bob

This will give you a list of user IDs that are friends with both Alice and Bob. It's that simple and incredibly fast!


Further Reading & References πŸ“š

Challenge

You are the data engineer for a major tech event company. You are tasked with managing the attendee lists for two concurrent conferences, DevCon and CodeFest, using Redis Sets.

Your goal is to write a sequence of Redis commands to perform the following operations in order:

  1. Create a set named attendees:devcon and add the following attendees: Alice, Bob, Charlie, David, Eve.
  2. Create a set named attendees:codefest and add the following attendees: Charlie, David, Frank, Bob.
  3. Find all attendees who are registered for both DevCon and CodeFest.
  4. Find all attendees who are registered for DevCon but not for CodeFest.
  5. An attendee, Eve, has just canceled her registration for DevCon. Remove her from the attendees:devcon set.
  6. A last-minute attendee, Grace, has just registered for CodeFest. Add her to the attendees:codefest set.
  7. Verify that Grace is now a member of the attendees:codefest set.
  8. The company needs a master list of every unique individual attending at least one of the conferences. Generate this combined list.

Expected result

Your solution should be a sequence of eight Redis commands that correctly perform each of the specified tasks in the given order. The correct commands are:

  1. SADD attendees:devcon "Alice" "Bob" "Charlie" "David" "Eve"
  2. SADD attendees:codefest "Charlie" "David" "Frank" "Bob"
  3. SINTER attendees:devcon attendees:codefest
  4. SDIFF attendees:devcon attendees:codefest
  5. SREM attendees:devcon "Eve"
  6. SADD attendees:codefest "Grace"
  7. SISMEMBER attendees:codefest "Grace"
  8. SUNION attendees:devcon attendees:codefest
redis

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.