Learnitweb

Redis Sets

Redis sets are unordered collections of unique items. They are similar to Java Sets. Sets are useful when you need to:

  • Store unique elements without duplicates.
  • Check for membership efficiently.
  • Perform operations like union, intersection, and difference.

Why Use Sets Instead of Lists?

While a list can store multiple items, a set has some advantages:

  1. No duplicates: Adding the same element multiple times will store it only once.
  2. Efficient membership check: Checking whether an element exists in a set is faster than searching through a list.
  3. Use cases:
    • Active users in a session: add on login, remove on logout.
    • Blacklist IP addresses: quickly check if a request should be blocked.
    • Tags, categories, or unique IDs where duplicates are not allowed.

Starting with Redis Sets

Step 1: Clear the Database

FLUSHDB

This ensures no old data interferes with our examples.


Step 2: Creating a Set and Adding Items

The main command to add items to a set is SADD.

SADD users 1 2 3 4 5
  • users is the key for our set.
  • You can add multiple items at once, or add items one by one:
SADD users 6
SADD users 7

Step 3: Checking the Size of a Set

To find how many unique items are in the set:

SCARD users
  • SCARD stands for Set Cardinality.
  • Returns the count of elements in the set.

Step 4: Viewing All Members of a Set

To see all items in a set:

SMEMBERS users

Notes:

  • The set is unordered, so items may not appear in the order they were added.
  • Duplicates are automatically ignored:
SADD users 3
  • Adding 3 again does nothing; the set still contains one 3.

Step 5: Checking Membership

To check if a particular element exists in a set:

SISMEMBER users 5

Output:

1   # Element exists
0   # Element does not exist
  • Returns 1 if the item is present, 0 if not.

Step 6: Removing Items

Remove a Specific Item

SREM users 5
  • Removes 5 from the set.
  • Returns 1 if the item was removed, 0 if it did not exist.

Randomly Remove an Item

SPOP users
  • Removes a random item from the set.
  • You can optionally specify how many items to pop:
SPOP users 2

Step 7: Practical Notes

  1. Order is not maintained: Sets are unordered; you cannot rely on the order of items.
  2. Efficient membership checks: Use SISMEMBER to quickly check presence.
  3. Duplicates are ignored: Adding the same item multiple times has no effect.
  4. Random removal: SPOP is useful when processing items randomly.

Redis sets provide a powerful and efficient way to manage unique collections of items, especially when membership checks and uniqueness are important.