redis之sets类型

 sets类型及操作

    Set是集合,它是string类型的无序集合。set是通过hash table实现的,添加、删除和查找的复杂度都是0(1)。对集合我们可以取并集、交集‘、差集。通过这些操作我们可以实现sns中好友推荐和blog的tag功能

一、sadd  向名称为key的set中添加元素

127.0.0.1:6379> sadd mysqt "hello"
(integer) 1
127.0.0.1:6379> sadd myset "hello"
(integer) 1
127.0.0.1:6379> sadd myset "one"
(integer) 1
127.0.0.1:6379> sadd myset "two"
(integer) 1
127.0.0.1:6379> sadd myset "two"
(integer) 0
127.0.0.1:6379> sadd myset three
(integer) 1
127.0.0.1:6379> smembers myset
1) "hello"
2) "one"
3) "three"
4) "two"

二、srem  删除名称为key的set中的元素

127.0.0.1:6379> srem myset two
(integer) 1
127.0.0.1:6379> smembers myset
1) "hello"
2) "one"
3) "three"

三、spop 随机返回并删除名称为key的set中的一个元素

127.0.0.1:6379> spop myset 1
1) "hello"
127.0.0.1:6379> spop myset 2
1) "one"
2) "three"
127.0.0.1:6379> smembers myset
(empty list or set)

四、sdiff 返回所有给定key与第一个key的差集

127.0.0.1:6379> sadd myset1 one
(integer) 1
127.0.0.1:6379> sadd myset1 two
(integer) 1
127.0.0.1:6379> sadd myset2 two
(integer) 1
127.0.0.1:6379> sadd myset three
(integer) 1
127.0.0.1:6379> sadd myset2 three
(integer) 1
127.0.0.1:6379> sdiff myset1 myset2
1) "one"
127.0.0.1:6379> sdiff myset2 myset1
1) "three"

五、sdiffstore  返回所有给定key与第一个key的差集,并将结果存为另一个key

127.0.0.1:6379> sdiffstore myset3 myset1 myset2
(integer) 1
127.0.0.1:6379> smembers myset3
1) "one"

六、sinter  返回所有给定key的交集

127.0.0.1:6379> sinter myset1 myset2
1) "two"

七、sinterstore   返回所有给定key的交集,并将结果存为另一个key

127.0.0.1:6379> sinterstore myset4 myset1 myset2
(integer) 1
127.0.0.1:6379> smembers myset4
1) "two"

八、sunion 返回所有给定key的并集

127.0.0.1:6379> sunion myset1 myset2
1) "one"
2) "three"
3) "two"

九、sunionstore  返回所有给定key的并集并保存到指定的集合中

127.0.0.1:6379> sunionstore myset5 myset1 myset2
(integer) 3
127.0.0.1:6379> smembers myset5
1) "one"
2) "three"
3) "two"
127.0.0.

十、smove  从第一个key对应的set中移除member并添加到第二个对应的set中

127.0.0.1:6379> smembers myset1
1) "one"
2) "two"
127.0.0.1:6379> smembers myset2
1) "three"
2) "two"
127.0.0.1:6379> smove myset2 myset1 three
(integer) 1
127.0.0.1:6379> smembers myset1
1) "one"
2) "three"
3) "two"

十一、scard  返回名称为key的set元素的个数

127.0.0.1:6379> scard myset1
(integer) 3
127.0.0.1:6379> scard myset2
(integer) 1

十二、sismember  测试member是否是名称为key的set元素

127.0.0.1:6379> sismember myset four
(integer) 0
127.0.0.1:6379> sismember myset three
(integer) 1

十三、srandmember  随机返回名称为key的set的一个元素,但不删除元素

127.0.0.1:6379> srandmember myset1
"two"
127.0.0.1:6379>
127.0.0.1:6379> srandmember myset1
"one"
127.0.0.1:6379> srandmember myset1
"three"

你可能感兴趣的:(redis之sets类型)