Redis笔记(set)

127.0.0.1:6379> help @set

SADD key member [member ...]
summary: Add one or more members to a set
since: 1.0.0

SCARD key
summary: Get the number of members in a set
since: 1.0.0

SDIFF key [key ...]
summary: Subtract multiple sets
since: 1.0.0

SDIFFSTORE destination key [key ...]
summary: Subtract multiple sets and store the resulting set in a key
since: 1.0.0

SINTER key [key ...]
summary: Intersect multiple sets
since: 1.0.0

SINTERSTORE destination key [key ...]
summary: Intersect multiple sets and store the resulting set in a key
since: 1.0.0

SISMEMBER key member
summary: Determine if a given value is a member of a set
since: 1.0.0

SMEMBERS key
summary: Get all the members in a set
since: 1.0.0

SMOVE source destination member
summary: Move a member from one set to another
since: 1.0.0

SPOP key [count]
summary: Remove and return one or multiple random members from a set
since: 1.0.0

SRANDMEMBER key [count]
summary: Get one or multiple random members from a set
since: 1.0.0

SREM key member [member ...]
summary: Remove one or more members from a set
since: 1.0.0

SSCAN key cursor [MATCH pattern] [COUNT count]
summary: Incrementally iterate Set elements
since: 2.8.0

SUNION key [key ...]
summary: Add multiple sets
since: 1.0.0

SUNIONSTORE destination key [key ...]
summary: Add multiple sets and store the resulting set in a key
since: 1.0.0

SADD命令用来创建一个set并添加值

Image for post

SCARD命令用来查询一个set里的成员数量

Image for post

SMEMBERS用来获取一个set中所有的成员的值(注意:如果set很大,这个命令会消耗Redis主机的网卡吞吐量)

Image for post

SREM可以删除set中的成员(支持移除多个)

Image for post

使用set可以进行交集,并集,差集的操作

比如现在有两个set,set1中有1,2,3,4,5,set2中有4,5,6,7,8

使用SINTER命令可以返回交集

Image for post

使用SINTERSTORE可以把交集存储到一个目标key中

Image for post

SUNION取并集同理

Image for post

SDIFF可以取差集,返回的是第一个key集合中有,而第二个key没有的成员

Image for post

使用SRANDMEMBER命令可以随意取值,从一个key中随机取值,如果参数count是正,取出一组不重复的结果,如果参数count是负数,取出这个数绝对值个的结果(如果范围超过set长度,值可重复),为0返回空。

Image for post
Image for post

还有一种随机取值可以将set中的值pop出来,就是SPOP命令,会从set中随机取值并从set中删除这个成员

Image for post

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store