What is Set in Redis?
A Set in Redis is an unordered set of unique string values. Every element is a Redis String, but with no duplicates and no preserved order.
Main properties
- Every element is unique (duplicates aren't stored).
- Element order isn't fixed.
- Fast set operations are supported, union, intersection, difference.
- It fits storing unique values: IDs, tags, users, and so on.
Example
bash
SADD users "anna" "ivan" "maria"
SADD users "ivan"
SMEMBERS usersResult:
javascript
1) "anna"
2) "ivan"
3) "maria"The second "ivan" add is ignored, the element already exists.
Main commands
| Command | Description |
|---|---|
SADD key value [value ...] | add element(s) |
SREM key value [value ...] | remove element(s) |
SMEMBERS key | get every element in the set |
SISMEMBER key value | check whether a value exists |
SCARD key | the number of elements |
SPOP key [count] | remove and return a random element |
SRANDMEMBER key [count] | get a random element without removing it |
SUNION key [key ...] | union of sets |
SINTER key [key ...] | intersection of sets |
SDIFF key [key ...] | difference of sets |
A union and intersection example
bash
SADD groupA "anna" "maria"
SADD groupB "maria" "ivan"
SUNION groupA groupB
SINTER groupA groupBResult:
javascript
SUNION → "anna", "maria", "ivan"
SINTER → "maria"Internal structure
Redis stores sets in two formats:
- intset, if every element is an integer and there aren't many (up to 512 elements by default).
- hashtable, if there are more elements or they include strings.
intset saves memory, hashtable provides fast insertion and lookup.
Uses
- Storing unique user IDs or tokens.
- Lists of subscribers or members with no duplicates.
- Fast membership checks (
SISMEMBER). - Recommendation systems via set intersection (
SINTER). - Counting unique visits or actions (
SCARD).
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.