Ch 4 · Redis Sets · Redis

Topic 4 of 5 in Redis — Complete Tutorial (Beginner) — 4 lessons.

Set Operations

Use Redis sets for unique collections, intersections, and unions. A set never holds the same member twice, so adding a duplicate simply has no effect. That makes sets perfect for tags, followers or unique visitors. You will add members with SADD, check membership quickly with SISMEMBER, and compare two sets with SINTER, SUNION and SDIFF.

Set Operations in Code

This example tags two blog posts, then compares their tag sets. See how SISMEMBER answers a yes-or-no question with 1 or 0, and SMEMBERS lists everything. Pay close attention to the set maths: SINTER finds the shared tag, SUNION merges both, and SDIFF keeps only what the first post has. SCARD counts members and SRANDMEMBER picks one at random.

Practice: Set Operations

Now use sets to compare two people's skills. You will create one set per user, find the skills they share, and then find the skills only the first user has. A correct answer shows you understand that the order of the keys matters for a difference but not for an intersection, and that sets never contain repeats.

Solution & Challenge: Set Operations

Check your answer against the worked solution, which gives Alice and Bob skill sets and prints both their shared skills and Alice's unique ones. The challenge goes further with a tagging system: tag items with SADD, find items by tag, discover related tags with SINTER, and rank tags by popularity using SCARD to count how many items each one has.

All topics in Redis Beginner

  1. Redis Hashes
  2. Redis Introduction and Setup
  3. Redis Lists
  4. Redis Sets
  5. Redis Strings and Numbers