陈大剩博客

Redis 集合(Sets) 复习

  • 陈大剩
  • 2022-09-10 16:08:59
  • 513

介绍

集合类似 Java 中的 HashSet,内部实现是一个 value 永远为 null 的 HashMap,实际就是通过计算hash的方式来快速排重的,这也是 set 能提供判断一个成员是否在集合内的原因。

应用场景

redis 的 sets 类型是使用哈希表构造的,因此复杂度是 o(1),它支持集合内的增删改查,并且支持多个集合间的交集、并集、差集操作。可以利用这些集合操作,解决程序开发过程当中很多数据集合间的问题。比如计算网站独立ip,用户画像中的用户标签,共同好友等功能

命令大纲

新增(SADD)

添加一个&多个成员(SADD)

SADD key member [member ...]

返回值:被添加到集合中的新元素的数量,不包括被忽略的元素。

# SADD key member [member ...]
> SADD testsets zhangsan lisi wangwu zhaoliu zhangsan
(integer) 4
> sadd testsets1 chendasheng zhansi liwu wangliu
(integer) 4

查询(SCARD、SMEMBERS、SISMEMBER、SDIFF、SDIFFSTORE、SINTER、SINTERSTORE、SUNION、SUNIONSTORE、SRANDMEMBER)

获取的成员数(SCARD)

SCARD key

返回值

集合的数量。 当集合 key 不存在时,返回 0 。

> SCARD testsets
(integer) 4

返回所有成员(SMEMBERS)

SMEMBERS key
> SMEMBERS testsets
1) "zhaoliu"
2) "wangwu"
3) "lisi"
4) "zhangsan"

> SMEMBERS testsets1
1) "wangliu"
2) "liwu"
3) "zhansi"
4) "chendasheng"

判断成员是否存在集合中(SISMEMBER)

 SISMEMBER key member

返回值

存在返回 1 不存在返回 0

> SISMEMBER testsets chendasheng
(integer) 0
> SISMEMBER testsets1 chendasheng
(integer) 1

查与其他集合的差异(SDIFF)【第一个与其它】

SDIFF key [key ...]

返回值

> SADD test1 1 2 3
> SADD test2 2 3 4
> SDIFF test1  test3
1) "1"
2) "2"

返回所有集合的差集存储在其他集合中(SDIFFSTORE)

# destination 储存的集合
SDIFFSTORE destination key [key ...]

返回值

> SDIFFSTORE test4 test1 test3
(integer) 2
> SMEMBERS test4
1) "1"
2) "2"

返回所有集合的交集(SINTER)

SINTER key [key ...]

返回值

> SINTER test1 test2
1) "2"
2) "3"

返回所有集合的交集存储在其他集合中(SINTERSTORE)

# destination 储存的集合
SINTERSTORE destination key [key ...]

返回值

> SINTERSTORE test5 test1 test4
(integer) 2
> SMEMBERS test5
1) "1"
2) "2"

返回所有集合的并集(SUNION)

SUNION key [key ...]

返回值

> SADD test1 1 2 3
> SADD test2 2 3 4
> SUNION test1 test2
1) "1"
2) "2"
3) "3"
4) "4"

返回所有集合的并集存储在其他集合中(SUNIONSTORE)

# destination 储存的集合
SUNIONSTORE destination key [key ...]

返回值

> SUNIONSTORE test6 test1 test2
(integer) 4
> SMEMBERS test6
1) "1"
2) "2"
3) "3"
4) "4"

返回集合中一个或多个随机数(SRANDMEMBER)

SRANDMEMBER key [count]

返回值

> SMEMBERS test6
1) "1"
2) "2"
3) "3"
4) "4"

删除

移除并返回集合中的一个或多个随机元素

SPOP key [count]

返回值

> SPOP test6 2
1) "2"
2) "1"
> SMEMBERS test6
1) "3"
2) "4"

移除集合中一个或多个成员

SREM key member [member ...]

返回值

> SREM test6 3 4
(integer) 2
> SMEMBERS test6
(empty array)

其他操作

将 member 元素从 source 集合移动到 destination 集合

SMOVE source destination member

返回值

> SMOVE test1 test2 1
(integer) 1
> SMEMBERS test1
1) "2"
2) "3"

迭代

SCAN cursor [MATCH pattern] [COUNT count] [TYPE type]

返回值

参考字符串迭代

本文参考&引用

Redis 集合(Set) | 菜鸟教程

Set(集合) — Redis 命令参考

分享到:
0

说点儿什么吧

头像

表情

本站由陈大剩博客程序搭建 | 湘ICP备2023000975号| Copyright © 2017 - 陈大剩博客 | 本站采用创作共用版权:CC BY-NC 4.0

站长统计| 文章总数[109]| 评论总数[9]| 登录用户[22]| 时间点[112]

logo

登入

社交账号登录