集合set:set集合是无序且不可重复的,set是通过hashtable实现的,添加删除和查找的复杂度都是O(1),效率很高。它最大的优势在于可以进行交集、冰机、差集操作。set集合中最大元素数量是4294967295。
应用场景:利用交集求共同好友。利用唯一性可以统计网站的所有独立ip。
- 添加set元素(重复元素不再添加)
127.0.0.1:6379> sadd set1 a b c
(integer) 3
127.0.0.1:6379> sadd set1 d s a
(integer) 2
- 查看指定集合元素
127.0.0.1:6379> smembers set1
1) "c"
2) "b"
3) "a"
4) "s"
5) "d"
- 删除元素
127.0.0.1:6379> srem set1 a b
(integer) 2
127.0.0.1:6379> smembers set1
1) "s"
2) "d"
3) "c"
- 判断某个元素是否存在,存在返回1,否则返回0
127.0.0.1:6379> sismember set1 d
(integer) 1
127.0.0.1:6379> sismember set1 a
(integer) 0
- sdiff计算差集(与集合放置的顺序有关,根据前者进行参考)
127.0.0.1:6379> sadd set2 a b c
(integer) 3
127.0.0.1:6379> sadd set3 b c d e f
(integer) 5
127.0.0.1:6379> sdiff set2 set3
1) "a"
127.0.0.1:6379> sdiff set3 set2
1) "d"
2) "f"
3) "e"
- sinter计算交集
127.0.0.1:6379> sinter set2 set3
1) "c"
2) "b"
- sunion计算并集
127.0.0.1:6379> sunion set2 set3
1) "a"
2) "f"
3) "b"
4) "d"
5) "c"
6) "e"
- scard计算元素总数
127.0.0.1:6379> smembers set1
1) "s"
2) "d"
3) "c"
127.0.0.1:6379> scard set1
(integer) 3
- srandmember随机取一个元素
127.0.0.1:6379> srandmember set1
"d"
127.0.0.1:6379> srandmember set1
"s"
- 把差集结果存入另一个新集合
127.0.0.1:6379> smembers set3
1) "f"
2) "b"
3) "d"
4) "c"
5) "e"
127.0.0.1:6379> sadd set4 a b c
(integer) 3
127.0.0.1:6379> smembers set4
1) "a"
2) "c"
3) "b"
127.0.0.1:6379> sdiffstore r1 set4 set3
(integer) 1
127.0.0.1:6379> smembers r1
1) "a"
- 把交集结果存入另一个新集合
127.0.0.1:6379> sinterstore s3 set3 set4
(integer) 2
127.0.0.1:6379> smembers s3
1) "c"
2) "b"
- 把并集结果存入另一个新集合
127.0.0.1:6379> sunionstore r2 set4 set3
(integer) 6
127.0.0.1:6379> smembers r2
1) "a"
2) "f"
3) "b"
4) "d"
5) "c"
6) "e"