Redis 简明教程

Redis - Sets

Redis 集合是一组无序的唯一字符串。唯一意味着集合不允许键中的数据重复。

Redis Sets are an unordered collection of unique strings. Unique means sets does not allow repetition of data in a key.

在 Redis 集合中添加、移除,以及测试成员是否存在的时间复杂度为 O(1)(常数时间,与集合中包含的元素数量无关)。列表的最大长度是 232 - 1 个元素(4294967295,每个集合超过 40 亿个元素)。

In Redis set add, remove, and test for the existence of members in O(1) (constant time regardless of the number of elements contained inside the Set). The maximum length of a list is 232 - 1 elements (4294967295, more than 4 billion of elements per set).

Example

redis 127.0.0.1:6379> SADD tutorials redis
(integer) 1
redis 127.0.0.1:6379> SADD tutorials mongodb
(integer) 1
redis 127.0.0.1:6379> SADD tutorials mysql
(integer) 1
redis 127.0.0.1:6379> SADD tutorials mysql
(integer) 0
redis 127.0.0.1:6379> SMEMBERS tutorials
1) "mysql"
2) "mongodb"
3) "redis"

在上述示例中,通过命令 SADD 向名为“教程”的 Redis 集合中插入三个值。

In the above example, three values are inserted in Redis set named ‘tutorials’ by the command SADD.

Redis Sets Commands

下表列出了与集合相关的一些基本命令。

Following table lists some basic commands related to sets.

Sr.No

Command & Description

1

SADD key member1 [member2]Adds one or more members to a set

2

SCARD keyGets the number of members in a set

3

SDIFF key1 [key2]Subtracts multiple sets

4

SDIFFSTORE destination key1 [key2]Subtracts multiple sets and stores the resulting set in a key

5

SINTER key1 [key2]Intersects multiple sets

6

SINTERSTORE destination key1 [key2]Intersects multiple sets and stores the resulting set in a key

7

SISMEMBER key memberDetermines if a given value is a member of a set

8

SMEMBERS keyGets all the members in a set

9

SMOVE source destination memberMoves a member from one set to another

10

SPOP keyRemoves and returns a random member from a set

11

SRANDMEMBER key [count]Gets one or multiple random members from a set

12

SREM key member1 [member2]Removes one or more members from a set

13

SUNION key1 [key2]Adds multiple sets

14

SUNIONSTORE destination key1 [key2]Adds multiple sets and stores the resulting set in a key

15

SSCAN key cursor [MATCH pattern] [COUNT count]Incrementally iterates set elements