Redis Sets are collections of unique string elements. Implemented as hash tables, they offer O(1) time complexity for insertions, deletions, and membership lookups. Each set can hold up to 2^32 - 1 unique members.
Accessing Command Documentation
You can list all available set operations directly via the CLI:
127.0.0.1:6379> help @set
Adding Elements
The SADD comand adds members to a set, creating the key if it does not exist.
127.0.0.1:6379> SADD inventory "alpha" "beta"
(integer) 2
Retrieving Members
Use SMEMBERS to fetch all elements currently in the collection.
127.0.0.1:6379> SMEMBERS inventory
1) "alpha"
2) "beta"
Removing Elements
SREM removes one or more specific members from a set.
127.0.0.1:6379> SREM inventory "alpha"
(integer) 1
Moving Members
SMOVE atomically moves a member from a source set to a destination set.
127.0.0.1:6379> SMOVE source_set target_set "item1"
(integer) 1
Checking Set Cardinality
SCARD returns the number of elements present in the set.
127.0.0.1:6379> SCARD inventory
(integer) 1
Random Element Retrieval
SRANDMEMBER returns one or more random items from the set without removing them.
127.0.0.1:6379> SRANDMEMBER inventory 2
1) "beta"
Verifying Membership
SISMEMBER checks if a specific value belongs to the collection.
127.0.0.1:6379> SISMEMBER inventory "beta"
(integer) 1
Popping Random Elements
SPOP removes and returns one or more random members from the set.
127.0.0.1:6379> SPOP inventory
"beta"
Intersections
SINTER identifies shared members across multiple sets, while SINTERSTORE saves the result into a new key.
127.0.0.1:6379> SINTERSTORE common_items setA setB
(integer) 2
Unions
SUNION combines multiple sets, excluding duplciates. SUNIONSTORE writes the result to a new key.
127.0.0.1:6379> SUNIONSTORE all_items setA setB
(integer) 5
Differences
SDIFF returns the members in the first set that are not present in subsequent sets. SDIFFSTORE saves this delta into a new key.
127.0.0.1:6379> SDIFFSTORE unique_items setA setB
(integer) 1