NoSQL database (2) 04-Redis data type - introduction to collection types, commands - adding and deleting elements, obtaining all elements in the collection, judging whether elements are in the collection, operations between collections

NoSQL database (2) 04-Redis data type - introduction to collection types, commands - adding and deleting elements, obtaining all elements in the collection, judging whether elements are in the collection, operations between collections

collection type

Redis has a data type that is very suitable for storing tags of articles, and it is a collection type.

introduce

The concept of set has been learned in high school mathematics class. Each element in a collection is distinct and has no order. A collection type (set) key can store up to 232-1 (I believe this number is already familiar to everyone) strings. Collection types and list types have similarities, but it is easy to distinguish them,

insert image description here

Common operations of the collection type are adding or deleting elements to the collection, judging whether an element exists, etc. Since the collection type is implemented in Redis using an empty hash table (hash table), the time complexity of these operations is Both are O(1). The most convenient thing is that union, intersection, and difference operations can also be performed between multiple collection type keys. You will see the convenience brought by the flexible use of this feature later.

Order

  1. add/remove elements

    SADD key member [member …]

    SREM key member [member …]

    The SADD command is used to add one or more elements to the collection, and will be created automatically if the key does not exist. Because there cannot be identical elements in a collection, if the element to be added already exists in the collection, this element will be ignored. The return value of this command is the number of elements successfully added (ignored elements are not counted). For example:

     redis> SADD letters a 
     (integer) 1 
     redis> SADD letters a b c 
     (integer) 2 
    

    The return value of the second SADD command is 2 because the element "a" already exists, so only two elements are actually added.

    The SREM command is used to delete one or more elements from the collection and return the number of successful deletions, for example:

     redis> SREM letters c d 
     (integer) 1 
    

    Since the element "d" does not exist in the set, only one element is removed and the return value is 1.

2. get all elements in the collection

SMEMBERS key

The SMEMBERS command returns all elements in the collection, for example:

redis> SMEMBERS letters 
1) "b" 
2) "a"
  1. Determine whether an element is in a collection

    SISMEMBER key member

    Determining whether an element is in a set is an O(1) operation. No matter how many elements are in the set, the SISMEMBER command can always return the result extremely quickly. Determining whether an element is in the set when the value exists is an operation with a time complexity of O(1). No matter how many elements are in the set, the SISMEMBER command can always return the result extremely fast. The SISMEMBER command returns 1 when the value exists and 0 when the value does not exist or the key does not exist, for example:

    redis> SISMEMBER letters a 
    (integer) 1 
    redis> SISMEMBER letters d 
    (integer) 0
    

4. operations between sets

SDIFF key [key „]

SINTER key [key „]

SUNION key [key „]

The next three commands to be introduced are all used to perform operations between multiple sets.

1) The SDIFF command is used to perform difference operations on multiple sets. The difference set of set A and set B is expressed as A−B, which represents the set of all elements belonging to A and not belonging to B (as shown in Figure 3-13), that is, A−B ={x | x∈A and x ∈B}. For example:

insert image description here

{1, 2, 3} - {2, 3, 4} = {1} {2, 3, 4} - {1, 2, 3} = {4} The SDIFF command is used as follows:

redis> SADD setA 1 2 3 
(integer) 3 
redis> SADD setB 2 3 4 
(integer) 3 
redis> SDIFF setA setB 
1) "1" 
redis> SDIFF setB setA 
1) "4"

The SDIFF command supports passing in multiple keys at the same time, for example:

redis> SADD setC 2 3 
(integer) 2 
redis> SDIFF setA setB setC 
1) "1"

(2) The SINTER command is used to perform intersection operations on multiple sets. The intersection of set A and set B is expressed as A ∩ B, which represents the set of all elements belonging to A and B (as shown in Figure 3-14), that is, A ∩ B ={x | x ∈ A and x ∈ B }.

For example: {1, 2, 3} ∩ {2, 3, 4} = {2, 3} The usage of the SINTER command is as follows:

redis> SINTER setA setB 
1) "2" 
2) "3"

The SINTER command also supports passing in multiple keys at the same time, such as:

redis> SINTER setA setB setC 
1) "2" 
2) "3"

(3) The SUNION command is used to perform union operations on multiple sets. The union of set A and set B is expressed as A∪B, which represents the set of all elements belonging to A or belonging to B (as shown in Figure 3-15), that is, A∪B = {x | x∈A or x ∈ B }.

For example: {1, 2, 3} ∪{2, 3, 4} = {1, 2, 3, 4}

insert image description here

redis> SUNION setA setB 
1) "1" 
2) "2" 
3) "3" 
4) "4"

The SUNION command also supports passing in multiple keys at the same time, for example:

redis> SUNION setA setB setC 
1) "1" 
2) "2"
3) "3" 
4) "4"

ex: Store article tags

Considering that all the tags of an article are different from each other, and there is no requirement for the order of these tags when displaying, we can use the collection type key to store the tags of the article.

For each article, use the key named post:article ID:tags to store the tags of the article. The specific operation is as pseudo code:

var redis = require('redis');
var client = new redis({
    
    
    // 配置
});

client.sadd('post:42:tags 杂文 技术文章 java');

client.srem('post:42:tags 杂文');

var tags = client.smembers('post:42:tags');

Using collection type keys to store tags is suitable for occasions where tags need to be added or deleted individually. For example, whether adding or deleting tags in the WordPress blog program is for a single tag (as shown in Figure 3-16), you can intuitively use the SADD and SREM commands to complete the operation.

On the other hand, in some places, users need to directly set all the tags and then upload and modify them together. Figure 3-17 shows the personal data editing page of a certain website. After users edit their hobbies and submit them, the program directly overwrites the original tag data. The whole process There is no operation for a single tag, and the advantage of the collection type is not used, so you can also directly use the string type key to store tag data at this time.

insert image description here

The reason why I specifically mentioned this difference in practice is to explain that there is no absolute rule for the choice of Redis storage method. For example, I introduced the use of list type to store visitor comments before, but in some specific occasions, hash type or even string type might be a better fit.

ex: Search articles by tags

Sometimes we also need to list all articles under a certain label, or even obtain a list of articles belonging to several labels at the same time. This requirement is more complicated to implement in traditional relational databases. Here is an example.

There are currently three tables, namely posts, tags and posts_tags, which respectively store article data, tags, and the corresponding relationship between articles and tags.

insert image description here

insert image description here

insert image description here

In order to find articles that belong to the three tags of "Java", "MySQL" and "Redis", the following SQL statement needs to be used:

SELECT p.post_title FROM posts_tags pt, posts p, tags t WHERE pt.tag_id = t.tag_id AND (t.tag_name IN ('Java', 'MySQL', 'Redis')) AND p.post_id = pt.post_id GROUP BY p.post_id HAVING COUNT(p.post_id)=3;

It is obvious to see that such SQL statements are not only relatively inefficient, but also difficult to read and maintain. Using Redis can achieve this requirement very simply and directly.

Use a name for each tag. The specific approach is to use a collection type key named tag:tag name:posts for each tag to store a list of post IDs tagged with that tag. Assume that there are now 3 articles with IDs 1, 2, and 3. The article with ID 1 has the tag "Java", the article with ID 2 has the tags "Java" and "MySQL", and the article with ID 3 has the tag "Java", "MySQL", and "Redis".

insert image description here

The simplest, you only need to use the command when you need to get the articles tagged with the "MySQL" tag SMEMBER Stag:MySQL:posts. If you want to find articles that belong to the three tags of Java, MySQL and Redis at the same time, you only need to take the intersection of the three keys tag:Java:posts, tag:MySQL:posts and tag:Redis:posts, and use the SINTER command to easily Finish.

command supplement

  1. Get the number of elements in the collection

SCARD key

redis> SMEMBERS letters 
1) "b" 
2) "a" 
redis> SCARD letters 
(integer) 2
  1. Perform set operations and store the results

    SDIFFSTORE destination key [key …]

    SINTERSTORE destination key [key …]

    SUNIONSTORE destination key [key …]

The SDIFFSTORE command has the same function as the SDIFF command, the only difference is that the former does not directly return the operation result, but stores the result in the destination key. The SDIFFSTORE command is often used in scenarios that require multi-step set operations. For example, it is necessary to calculate the difference first and then calculate the intersection of the result with other keys. The SINTERSTORE and SUNIONSTORE commands are similar and will not be repeated here.

  1. Randomly get the elements in the collection

    SRANDMEMBER key [count]

redis> SRANDMEMBER letters 
"a" 
redis> SRANDMEMBER letters 
"b" 
redis> SRANDMEMBER letters 
"a"

You can also pass the count parameter to randomly obtain multiple elements at a time. Depending on the positive or negative of the count, the specific performance is also different.

(1) When count is a positive number, SRANDMEMBER will randomly obtain count unique elements from the collection. If the value of count is greater than the number of elements in the collection, SRANDMEMBER will return all the elements in the collection.

(2) When count is negative, SRANDMEMBER will randomly obtain |count| elements from the collection, and these elements may be the same.

4. Pop an element from a collection

SPOP key

We have learned the LPOP command, which is used to pop an element from the left of the list (that is, return the value of the element and delete it). The function of the SPOP command is similar, but because the elements of the collection type are unordered, the SPOP command will randomly select an element from the collection to pop up .

example

set_demo.js

var redis = require('redis');
var client = new redis({
    
    

});

// 存储标签  post:id:comments  post:id:tags

client.sadd('post:42:tags 杂文 技术 java nodejs');  //存储
client.srem('post:42:tags 技术'); 

var tags = client.smember('post:42:tags');

emo.js

var redis = require('redis');
var client = new redis({
    
    

});

// 存储标签  post:id:comments  post:id:tags

client.sadd('post:42:tags 杂文 技术 java nodejs');  //存储
client.srem('post:42:tags 技术'); 

var tags = client.smember('post:42:tags');

Guess you like

Origin blog.csdn.net/weixin_44867717/article/details/131650919