Redis Set

A Redis Set is an unordered collection of String type. Set members are unique, which means that duplicate data cannot appear in a set.

The encoding of a set object can be intset or hashtable.

In Redis, sets are implemented via hash tables, so the complexity of add, delete, and lookup is O(1).

The maximum number of members in a set is 2^3232-1 (4294967295, each set can store over 4 billion members).

Example

redis 127.0.0.1:6379> SADD examplekey redis
(integer) 1
redis 127.0.0.1:6379> SADD examplekey mongodb
(integer) 1
redis 127.0.0.1:6379> SADD examplekey mysql
(integer) 1
redis 127.0.0.1:6379> SADD examplekey mysql
(integer) 0
redis 127.0.0.1:6379> SMEMBERS examplekey

1) "mysql"
2) "mongodb"
3) "redis"

In the above example, weSADDuse the command to insert into the namedexamplekeyset three elements.


Redis Set Commands

The following table lists the basic Redis Set commands:

No.Command and Description
1SADD key member1 [member2]
Add one or more members to a set
2SCARD key
Get the number of members in a set
3SDIFF key1 [key2]
Return the difference between the first set and other sets.
4SDIFFSTORE destination key1 [key2]
Return the difference of all given sets and store it in destination
5SINTER key1 [key2]
Return the intersection of all given sets
6SINTERSTORE destination key1 [key2]
Return the intersection of all given sets and store it in destination
7SISMEMBER key member
Determine whether the member element is a member of the set key
8SMEMBERS key
Return all members of a set
9SMOVE source destination member
Move the member element from the source set to the destination set
10SPOP key
Remove and return a random element from a set
11SRANDMEMBER key [count]
Return one or more random elements from a set
12SREM key member1 [member2]
Remove one or more members from a set
13SUNION key1 [key2]
Return the union of all given sets
14SUNIONSTORE destination key1 [key2]
Store the union of all given sets in the destination set
15SSCAN key cursor [MATCH pattern] [COUNT count]
Iterate over the elements in a set
Other Extensions