Redis Basics

Lesson 4 of 5

The Connection Web

Concept:

Redis Sets store unique, unordered elements — no duplicates allowed. This makes them perfect for problems where uniqueness matters: tracking unique visitors (SADD each visitor, SCARD to count), tagging systems (each tag is a set of items), and social features like mutual friends (SINTER to find common connections). Set operations (union, intersection, difference) happen server-side in microseconds, which would take multiple queries in a traditional database.
Detective Indecks: Two suspects, dozens of known associates. There's got to be a connection—someone who knows them both. That's my smoking gun.
REDIS: Sounds like you need Sets, detective. Perfect for tracking unique relationships and finding overlaps. No duplicates, no confusion—just clean connections.
Detective Indecks: How do I map out their networks?
REDIS: Use `SADD` to build each suspect's associate network. For example: `SADD known_associates:alpha "murphy"` adds Murphy to Alpha's network. Add as many as you need—Sets automatically handle uniqueness.
Detective Indecks: And to find the connection between them?
REDIS: `SINTER known_associates:alpha known_associates:bravo` gives you the intersection—everyone who appears in both networks. Your common connections, your potential witnesses.
Detective Indecks: What about checking if someone specific is in a network?
REDIS: `SISMEMBER known_associates:alpha "murphy"` returns 1 if Murphy knows Alpha, 0 if not. Quick membership checks. And `SREM` removes someone from a network if they turn out to be a dead end.
Detective Indecks: Beautiful. Time to map these connections and find my link.
Example Code:
SADD known_associates:alpha "murphy" "valdez" "chen"
SADD known_associates:bravo "murphy" "torres" "kim"
SINTER known_associates:alpha known_associates:bravo

Your Assignment

Build associate networks for suspects alpha and bravo. Alpha knows murphy, valdez, and chen. Bravo knows murphy, torres, and kim. Find their common connections.

Redis Console
redis>