redis数据类型:sets

sets类型及操作:

set是集合,它是string类型的无序集合。set是通过hash table实现的,

添加、删除和查找的复杂度都是O(1).对集合我们可以取并集、交集、差集。

通过这些操作我们可以实现sns中好友推荐(如QQ)和blog的tag(标签)功能。

sadd方法:添加元素

smembers方法:查看集合的所有成员

127.0.01:6379> SADD set "one" "two"
(integer) 2
127.0.01:6379> SMEMBERS set
1) "two"
2) "one"

srem方法:删除集合元素

127.0.01:6379> SMEMBERS set
1) "two"
2) "one"
127.0.01:6379> SREM set "one"
(integer) 1
127.0.01:6379> SMEMBERS set
1) "two"

spop方法:随机返回并删除名称为key的集合元素

127.0.01:6379> sadd set "two"
(integer) 0
127.0.01:6379> sadd set "one"
(integer) 1
127.0.01:6379> sadd set "three"
(integer) 1
127.0.01:6379> sadd set "four"
(integer) 1
127.0.01:6379> sadd set "five"
(integer) 1
127.0.01:6379> spop set
"five"
127.0.01:6379> spop set
"one"
127.0.01:6379> spop set
"three"
127.0.01:6379>

sdiff方法:两个集合的差集

127.0.01:6379> sadd set1 "one" "two"
(integer) 2
127.0.01:6379> sadd set2 "three" "two"
(integer) 2
127.0.01:6379> SMEMBERS set1
1) "two"
2) "one"
127.0.01:6379> SMEMBERS set2
1) "two"
2) "three"
127.0.01:6379> SDIFF set1 set2
1) "one"
127.0.01:6379> SDIFF set2 set1
1) "three"

sdiffstore方法:将两个集合的差集存到一个集合中

127.0.01:6379> SMEMBERS set2
1) "one"
2) "two"
3) "three"
127.0.01:6379> SMEMBERS set1
1) "three"
127.0.01:6379> SDIFF set1 set2
(empty list or set)
127.0.01:6379> SDIFF set2 set3
1) "three"
2) "two"
3) "one"
127.0.01:6379> SDIFF set2 set1
1) "two"
2) "one"
127.0.01:6379> SDIFFstore set3  set2 set1
(integer) 2
127.0.01:6379> SMEMBERS set3
1) "two"
2) "one"

sinter取两个集合的交集:

127.0.01:6379> sinter set1 set2
1) "three"

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

127.0.01:6379> sinterstore set4 set1 set2
(integer) 1
127.0.01:6379> SMEMBERS set4
1) "three"

sunion返回所有给定key的集合的并集

127.0.01:6379> sunion set1 set2
1) "two"
2) "one"
3) "three"

sunionstore 将并集存储到另一个集合中

127.0.01:6379> sunionstore set5 set1 set2
(integer) 3
127.0.01:6379> SMEMBERS set5
1) "two"
2) "one"
3) "three"

smove方法:从第一个key对应的set中指定元素移动到第二个集合中

127.0.01:6379> SMEMBERS set5
1) "two"
2) "one"
3) "three"
127.0.01:6379> smove set5 set6 one
(integer) 1
127.0.01:6379> SMEMBERS set5
1) "two"
2) "three"
127.0.01:6379> SMEMBERS set6
1) "one"

scard方法:查看集合中的元素个数

127.0.01:6379> SMEMBERS set5
1) "two"
2) "three"
127.0.01:6379> scard set5
(integer) 2

sismember方法:测试指定的元素是否是集合中的元素

127.0.01:6379> SMEMBERS set5
1) "two"
2) "three"
127.0.01:6379> SISMEMBER set5 "two"
(integer) 1

srandmember方法:随机返回名称为key的set的一个元素,但不删除元素

127.0.01:6379> SMEMBERS set5
1) "two"
2) "three"
127.0.01:6379> SRANDMEMBER set5
"three"
127.0.01:6379> SRANDMEMBER set5
"three"
127.0.01:6379> SRANDMEMBER set5
"three"
127.0.01:6379> SRANDMEMBER set5
"two"

上一篇:Web api dynamic


下一篇:C#:关于C#4中IEnumerable的理解