cs
A Redis set is a collection of unique elements stored under a single key.
Unlike lists, sets have two important properties:
- Elements are unique (duplicates are not allowed).
- Elements are not ordered.
Example conceptually:
online_users → {"user1", "user2", "user3"}
If you attempt to add the same element again, Redis simply ignores it.
Because of this property, sets are useful for problems where uniqueness matters.
Common uses include:
- tracking unique visitors
- storing tags
- membership checks
- relationships between objects
Adding Elements
SADD
Adds one or more elements to a set.
SADD users "alice"
SADD users "bob"
If "alice" is added again:
SADD users "alice"
The set remains unchanged because duplicates are not allowed.
Viewing Elements
SMEMBERS
Returns all members of a set.
SMEMBERS users
Output might look like:
1) "alice"
2) "bob"
The order is not guaranteed because sets are unordered.
Checking Membership
SISMEMBER
Checks whether a value exists in a set.
SISMEMBER users "alice"
Output:
(integer) 1
If the element does not exist:
(integer) 0
This operation is extremely fast and is often used for permission checks or membership validation.
Removing Elements
SREM
Removes an element from the set.
SREM users "alice"
After removal:
SMEMBERS users
Result:
"bob"
Set Operations
Redis can also perform mathematical set operations.
SINTER (Intersection)
Returns elements present in both sets.
SADD group1 "alice" "bob"
SADD group2 "bob" "charlie"
SINTER group1 group2
Result:
"bob"
SUNION (Union)
Returns elements from both sets combined.
SUNION group1 group2
Result:
"alice"
"bob"
"charlie"
SDIFF (Difference)
Returns elements that exist in one set but not the other.
SDIFF group1 group2
Result:
"alice"
Example Use Case
Tracking online users.
When a user logs in:
SADD online_users user123
When the user logs out:
SREM online_users user123
Checking if a user is online:
SISMEMBER online_users user123
This approach is fast, simple, and avoids duplicate entries.
Related: [[Redis]] [[Redis - Strings]] [[Redis - Lists]] [[Redis - Hashes]] [[Redis-sorted-sets]