In Redis, a Set is an unordered collection of unique String elements. This means that duplicate values are not allowed within a Set.

The Set’s underlying data structure can either be an intset or a hashtable.

Since Redis Sets are implemented using hash tables, the time complexity for adding, removing, or checking for members is O(1).

A Set can have a maximum of 2^32 - 1 (4,294,967,295) members, which means each Set can store over 4 billion elements.

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
127.0.0.1:6379> SADD s_db redis
(integer) 1
127.0.0.1:6379> SADD s_db hbase
(integer) 1
127.0.0.1:6379> SADD s_db mysql
(integer) 1
127.0.0.1:6379> SADD s_db mysql
(integer) 0
127.0.0.1:6379> SMEMBERS s_db
1) "mysql"
2) "hbase"
3) "redis"
127.0.0.1:6379>

In the above example, we used the SADD command to add three elements to the set named s_db. When attempting to add "mysql" a second time, Redis returns 0 since it already exists in the Set.

Common Redis Set Commands

Here’s a list of basic Redis Set commands:

No. Command & Description
1 SADD key member1 [member2]
Add the specified members to the set stored at key.
2 SCARD key
3 SDIFF key1 [key2]
4 SDIFFSTORE destination key1 [key2]
5 SINTER key1 [key2]
6 SINTERSTORE destination key1 [key2]
7 SISMEMBER key member
8 SMEMBERS key
9 SMOVE source destination member
10 SPOP key
11 SRANDMEMBER key [count]
12 SREM key member1 [member2]
13 SUNION key1 [key2]
14 SUNIONSTORE destination key1 [key2]
15 SSCAN key cursor [MATCH pattern] [COUNT count]