Redis 集合set 操作
Redis 集合set 操作

Redis 集合set 操作
• 发表于 10个月前
• 阅读 13
• 收藏 0
• 评论 0

### 添加集合

``````127.0.0.1:6379> sadd gender male female yao
(integer) 2
``````

### 删除集合中的元素

#### srem key value ：删除固定元素

``````127.0.0.1:6379> srem gender yao
(integer) 1
``````

#### spop key value : 随机删除1个元素

``````127.0.0.1:6379> spop gender
"female"
``````

### 查看集合中的元素

#### smembers key:查看所有元素

``````127.0.0.1:6379> smembers gender
1) "yao"
2) "female"
3) "male"
``````

#### srandmember key [count] :随机查看元素

``````127.0.0.1:6379> sadd a1 2 4 5 6 4
(integer) 4
127.0.0.1:6379> srandmember a1
"2"
127.0.0.1:6379> srandmember a1 2
1) "2"
2) "6"
``````

### 判断集合中是否有某一元素

#### sismember key value

``````127.0.0.1:6379> sismember a1 2
(integer) 1
127.0.0.1:6379> sismember a1 100
(integer) 0
``````

### 查看集合中共有多少个元素

#### scard key

``````127.0.0.1:6379> scard a1
(integer) 4
``````

### 将某个集合中的元素移动到另1个集合当中

#### smove source destination member

``````127.0.0.1:6379> sadd upper A B C              # 创建集合 upper
(integer) 3
127.0.0.1:6379> sadd lower a b c              # 创建集合 lower
(integer) 3
127.0.0.1:6379> smove lower upper a           # 从 lower 集合中移动元素 a 到集合 upper
(integer) 1
127.0.0.1:6379> smembers upper                # 查看 upper 集合中所有的元素
1) "C"
2) "a"
3) "B"
4) "A"
``````

### sinter a b :求交集

``````127.0.0.1:6379> sadd a1 1 2 3 4 5 6
(integer) 6
127.0.0.1:6379> sadd a2 2 3 4 6 7 5 9
(integer) 7
127.0.0.1:6379> sinter a1 a2
1) "2"
2) "3"
3) "4"
4) "5"
5) "6"
``````

### 求并集

#### sunion a1 a2

``````127.0.0.1:6379> sunion a1 a2
1) "1"
2) "2"
3) "3"
4) "4"
5) "5"
6) "6"
7) "7"
8) "9"
``````

### 求差集

#### sdiff key [key]

``````127.0.0.1:6379> sdiff a1 a2
1) "1"
``````

×