Home Backend Development C#.Net Tutorial Redis tutorial (5): Set data type

Redis tutorial (5): Set data type

Dec 28, 2016 pm 02:41 PM
redis

1. Overview:

In Redis, we can regard the Set type as an unsorted character collection. Like the List type, we can also add, delete, or delete data values ​​of this type. Determine whether an element exists and other operations. It should be noted that the time complexity of these operations is O(1), that is, the operations are completed in constant time. The maximum number of elements that a Set can contain is 4294967295.
Unlike the List type, duplicate elements are not allowed in the Set collection, which is exactly the same as the set container in the C++ standard library. In other words, if you add the same element multiple times, only one copy of the element will be kept in the Set. Compared with the List type, the Set type also has a very important functional feature, that is, the aggregation calculation operations between multiple Sets, such as unions, intersections, and differences, are completed on the server side. Since these operations are completed on the server side, they are extremely efficient and save a lot of network IO overhead.

2. Related command list:

##SDIFFkey [key ...]O(N)The N in time complexity represents the total number of members in all Sets. Returns the difference between the members in the Set associated with the first Key in the parameter and the Sets associated with all subsequent Keys. If Key does not exist, it is considered an empty Set. A collection of difference result membersSDIFFSTOREdestination key [key ...] O(NThis command is the same as SDIFF The commands are functionally identical, the only difference between the two is that SDIFF returns the result member of the difference, whereas this command stores the difference member in the Set associated with the destination. If the destination key already exists, this operation overwrites its members. Return the number of difference members ##SINTERkey [key ...] ##SINTERSTOREdestination key [key ...] O(N*M) This command is functionally identical to the SINTER command. The only difference between the two is that SINTER returns the result members of the intersection, while this command returns the intersection members. Stored in the Set associated with destination. If the destination key already exists, this operation will overwrite its members Return the number of intersection members O(N)##SUNIONSTOREdestination key [key ...] O(N)This command is functionally identical to the SUNION command. The only difference between the two is that SUNION returns the result members of the union, while this command stores the union members in the Set associated with the destination. If the destination key already exists. The operation will overwrite its members Returns the number of union members.

3. Command examples:

1. SADD/SMEMBERS/SCARD/SISMEMBER:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

#在Shell命令行下启动Redis的客户端程序。

    /> redis-cli

    #插入测试数据,由于该键myset之前并不存在,因此参数中的三个成员都被正常插入。

    redis 127.0.0.1:6379> sadd myset a b c

    (integer) 3

    #由于参数中的a在myset中已经存在,因此本次操作仅仅插入了d和e两个新成员。

    redis 127.0.0.1:6379> sadd myset a d e

    (integer) 2

    #判断a是否已经存在,返回值为1表示存在。

    redis 127.0.0.1:6379> sismember myset a

    (integer) 1

    #判断f是否已经存在,返回值为0表示不存在。

    redis 127.0.0.1:6379> sismember myset f

    (integer) 0

    #通过smembers命令查看插入的结果,从结果可以,输出的顺序和插入顺序无关。

    redis 127.0.0.1:6379> smembers myset

    1) "c"

    2) "d"

    3) "a"

    4) "b"

    5) "e"

    #获取Set集合中元素的数量。

    redis 127.0.0.1:6379> scard myset

    (integer) 5

Copy after login

2. SPOP/SREM/SRANDMEMBER/SMOVE:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

#删除该键,便于后面的测试。

    redis 127.0.0.1:6379> del myset

    (integer) 1

    #为后面的示例准备测试数据。

    redis 127.0.0.1:6379> sadd myset a b c d

    (integer) 4

    #查看Set中成员的位置。

    redis 127.0.0.1:6379> smembers myset

    1) "c"

    2) "d"

    3) "a"

    4) "b"

    #从结果可以看出,该命令确实是随机的返回了某一成员。

    redis 127.0.0.1:6379> srandmember myset

    "c"

    #Set中尾部的成员b被移出并返回,事实上b并不是之前插入的第一个或最后一个成员。

    redis 127.0.0.1:6379> spop myset

    "b"

    #查看移出后Set的成员信息。

    redis 127.0.0.1:6379> smembers myset

    1) "c"

    2) "d"

    3) "a"

    #从Set中移出a、d和f三个成员,其中f并不存在,因此只有a和d两个成员被移出,返回为2。

    redis 127.0.0.1:6379> srem myset a d f

    (integer) 2

    #查看移出后的输出结果。

    redis 127.0.0.1:6379> smembers myset

    1) "c"

    #为后面的smove命令准备数据。

    redis 127.0.0.1:6379> sadd myset a b

    (integer) 2

    redis 127.0.0.1:6379> sadd myset2 c d

    (integer) 2

    #将a从myset移到myset2,从结果可以看出移动成功。

    redis 127.0.0.1:6379> smove myset myset2 a

    (integer) 1

    #再次将a从myset移到myset2,由于此时a已经不是myset的成员了,因此移动失败并返回0。

    redis 127.0.0.1:6379> smove myset myset2 a

    (integer) 0

    #分别查看myset和myset2的成员,确认移动是否真的成功。

    redis 127.0.0.1:6379> smembers myset

    1) "b"

    redis 127.0.0.1:6379> smembers myset2

    1) "c"

    2) "d"

    3) "a"

Copy after login

3. SDIFF/SDIFFSTORE/SINTER/SINTERSTORE:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

#为后面的命令准备测试数据。

   redis 127.0.0.1:6379> sadd myset a b c d

   (integer) 4

   redis 127.0.0.1:6379> sadd myset2 c

   (integer) 1

   redis 127.0.0.1:6379> sadd myset3 a c e

   (integer) 3

   #myset和myset2相比,a、b和d三个成员是两者之间的差异成员。再用这个结果继续和myset3进行差异比较,b和d是myset3不存在的成员。

   redis 127.0.0.1:6379> sdiff myset myset2 myset3

   1) "d"

   2) "b"

   #将3个集合的差异成员存在在diffkey关联的Set中,并返回插入的成员数量。

   redis 127.0.0.1:6379> sdiffstore diffkey myset myset2 myset3

   (integer) 2

   #查看一下sdiffstore的操作结果。

   redis 127.0.0.1:6379> smembers diffkey

   1) "d"

   2) "b"

   #从之前准备的数据就可以看出,这三个Set的成员交集只有c。

   redis 127.0.0.1:6379> sinter myset myset2 myset3

   1) "c"

   #将3个集合中的交集成员存储到与interkey关联的Set中,并返回交集成员的数量。

   redis 127.0.0.1:6379> sinterstore interkey myset myset2 myset3

   (integer) 1

   #查看一下sinterstore的操作结果。

   redis 127.0.0.1:6379> smembers interkey

   1) "c"

   #获取3个集合中的成员的并集。   

   redis 127.0.0.1:6379> sunion myset myset2 myset3

   1) "b"

   2) "c"

   3) "d"

   4) "e"

   5) "a"

   #将3个集合中成员的并集存储到unionkey关联的set中,并返回并集成员的数量。

   redis 127.0.0.1:6379> sunionstore unionkey myset myset2 myset3

   (integer) 5

   #查看一下suiionstore的操作结果。

   redis 127.0.0.1:6379> smembers unionkey

   1) "b"

   2) "c"

   3) "d"

   4) "e"

   5) "a"

Copy after login

4. Application scope:


## 1). You can use the Set data type of Redis to track some Unique data, such as the unique IP address information for visiting a certain blog. For this scenario, we only need to store the visitor's IP in Redis every time we visit the blog, and the Set data type will automatically ensure the uniqueness of the IP address.

2). Make full use of the convenient and efficient features of Set type server-side aggregation operations, which can be used to maintain the association between data objects. For example, all customer IDs who purchase a certain electronic device are stored in a specified Set, and customer IDs who purchase another electronic product are stored in another Set. If at this time we want to get which customers purchased this at the same time, When there are two commodities, Set's intersections command can give full play to its advantages of convenience and efficiency.

The above is the content of Redis tutorial (5): Set data type. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!



Command prototype Time complexity Command description Return value
SADDkey member [member ...] O(N) The N in time complexity represents the number of members of the operation. If used during the insertion process, some members in the parameters already exist in the Set, the member will be ignored, and other members will still be inserted normally. If the Key does not exist before executing this command, this command will create a new Set, and then insert the members in the parameters one after another. If the Key's Value is not of Set type, this command will return relevant error information. The number of members actually inserted in this operation.
SCARDkey O(1) Get the number of members in the Set. Returns the number of members in the Set. If the Key does not exist, returns 0.
SISMEMBER key member O(1) Determine whether the member specified in the parameter already exists in the Set collection associated with the Key. 1 means it already exists, 0 means it does not exist, or the Key itself does not exist.
SMEMBERS key O(N) The N in time complexity represents the number of members that already exist in the Set. Get all members in the Set associated with the Key. Return all members in Set.
SPOPkey O(1) Randomly remove and return a member of the Set. Since the layout of the elements in a Set is not controlled externally, it is impossible to determine which element is at the head or tail of the Set like a List. Return the removed member. If the Key does not exist, return nil.
SREMkey member [member ...] O(N) The N in time complexity represents the number of deleted members. Delete the member specified in the parameter from the Set associated with the Key. Parameter members that do not exist will be ignored. If the Key does not exist, it will be treated as an empty Set. The number of members actually removed from the Set, if there are none, 0 is returned.
SRANDMEMBER key O(1) Same as SPOP, randomly returns a member of the Set. The difference is that this command does not Returned members will be deleted. Returns the member at a random position, or nil if the Key does not exist.
SMOVEsource destination member O(1) Atomicly move the member in the parameter from the source key to the Set associated with the destination key middle. So at a certain moment, the member either appears in the source or in the destination. If the member does not exist in the source, this command will perform no further operations and return 0. Otherwise, the member will be moved from the source to the destination. If the member already exists in the destination at this time, then this command only removes the member from the source.If the Value associated with Key is not a Set, relevant error information will be returned. 1 means normal movement, 0 means the source does not contain parameter members
O(N*M) Time N in complexity represents the number of elements in the minimum Set, and M represents the number of Sets in the parameter. This command will return the intersection of the members in the Sets associated with all Keys in the parameter. Therefore, if the Set associated with any Key in the parameter is empty. , or a key does not exist, then the result of this command will be an empty set The set of intersection result members
##SUNION key [key. ...]
N in time complexity represents the total number of members in all Sets. This command will return the union of members in Sets associated with all Keys in the parameter. Set. The set of union result members
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to build the redis cluster mode How to build the redis cluster mode Apr 10, 2025 pm 10:15 PM

Redis cluster mode deploys Redis instances to multiple servers through sharding, improving scalability and availability. The construction steps are as follows: Create odd Redis instances with different ports; Create 3 sentinel instances, monitor Redis instances and failover; configure sentinel configuration files, add monitoring Redis instance information and failover settings; configure Redis instance configuration files, enable cluster mode and specify the cluster information file path; create nodes.conf file, containing information of each Redis instance; start the cluster, execute the create command to create a cluster and specify the number of replicas; log in to the cluster to execute the CLUSTER INFO command to verify the cluster status; make

How to clear redis data How to clear redis data Apr 10, 2025 pm 10:06 PM

How to clear Redis data: Use the FLUSHALL command to clear all key values. Use the FLUSHDB command to clear the key value of the currently selected database. Use SELECT to switch databases, and then use FLUSHDB to clear multiple databases. Use the DEL command to delete a specific key. Use the redis-cli tool to clear the data.

How to use the redis command How to use the redis command Apr 10, 2025 pm 08:45 PM

Using the Redis directive requires the following steps: Open the Redis client. Enter the command (verb key value). Provides the required parameters (varies from instruction to instruction). Press Enter to execute the command. Redis returns a response indicating the result of the operation (usually OK or -ERR).

How to read redis queue How to read redis queue Apr 10, 2025 pm 10:12 PM

To read a queue from Redis, you need to get the queue name, read the elements using the LPOP command, and process the empty queue. The specific steps are as follows: Get the queue name: name it with the prefix of "queue:" such as "queue:my-queue". Use the LPOP command: Eject the element from the head of the queue and return its value, such as LPOP queue:my-queue. Processing empty queues: If the queue is empty, LPOP returns nil, and you can check whether the queue exists before reading the element.

How to use redis lock How to use redis lock Apr 10, 2025 pm 08:39 PM

Using Redis to lock operations requires obtaining the lock through the SETNX command, and then using the EXPIRE command to set the expiration time. The specific steps are: (1) Use the SETNX command to try to set a key-value pair; (2) Use the EXPIRE command to set the expiration time for the lock; (3) Use the DEL command to delete the lock when the lock is no longer needed.

How to read the source code of redis How to read the source code of redis Apr 10, 2025 pm 08:27 PM

The best way to understand Redis source code is to go step by step: get familiar with the basics of Redis. Select a specific module or function as the starting point. Start with the entry point of the module or function and view the code line by line. View the code through the function call chain. Be familiar with the underlying data structures used by Redis. Identify the algorithm used by Redis.

How to solve data loss with redis How to solve data loss with redis Apr 10, 2025 pm 08:24 PM

Redis data loss causes include memory failures, power outages, human errors, and hardware failures. The solutions are: 1. Store data to disk with RDB or AOF persistence; 2. Copy to multiple servers for high availability; 3. HA with Redis Sentinel or Redis Cluster; 4. Create snapshots to back up data; 5. Implement best practices such as persistence, replication, snapshots, monitoring, and security measures.

How to use the redis command line How to use the redis command line Apr 10, 2025 pm 10:18 PM

Use the Redis command line tool (redis-cli) to manage and operate Redis through the following steps: Connect to the server, specify the address and port. Send commands to the server using the command name and parameters. Use the HELP command to view help information for a specific command. Use the QUIT command to exit the command line tool.

See all articles