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:
- No duplicates: Adding the same element multiple times will store it only once.
- Efficient membership check: Checking whether an element exists in a set is faster than searching through a list.
- 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
usersis 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
SCARDstands 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
3again does nothing; the set still contains one3.
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
1if the item is present,0if not.
Step 6: Removing Items
Remove a Specific Item
SREM users 5
- Removes
5from the set. - Returns
1if the item was removed,0if 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
- Order is not maintained: Sets are unordered; you cannot rely on the order of items.
- Efficient membership checks: Use
SISMEMBERto quickly check presence. - Duplicates are ignored: Adding the same item multiple times has no effect.
- Random removal:
SPOPis 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.
