Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the operation instructions of common data types in Redis

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >

Share

Shulou(Shulou.com)05/31 Report--

This article will explain in detail what are the operation instructions of common data types in Redis. The editor thinks it is very practical, so I share it with you as a reference. I hope you can get something after reading this article.

The Redis command is used to perform operations on the redis service. A redis is required to execute commands on the redis service

Client. You can use the redis-cli command to start the Redis client. The complete startup command is redis-cli-h host-p port-a password.

There are five common data types in Redis: string, hash, list, set, and zset (sorted set ordered sets). Before learning these types, you also need to learn the management of the commonly used command Key. These types are described in detail below: a more detailed API can be found here

Common commands Key Management

Application scenarios of Key:

Information about time-limited discount activities.

The data cache of the website (for some data that needs to be updated regularly, such as points rankings)

Mobile phone verification code

Limit the frequency of website visitors (for example, up to 10 visits per minute)

Naming recommendations for Key:

Key names are case-sensitive; key should not be too long, and try not to exceed 1024 bytes, as too long will reduce the efficiency of lookup; it is best to use a uniform naming pattern, such as user:id:password, in a project.

Keys pattern returns all key that satisfy a given pattern, which can be blurred. For example, keys abc* represents key at the beginning of abc.

Exists key determines whether a key exists. If it exists, it returns 1. If it does not, it returns 0.

Expire key second sets the active time of a key (seconds)

Pexpire key milliseconds sets the active time of a key (milliseconds)

Del key deletes a key

Ttl key returns the remaining time of a key. If the key does not exist, it returns-2. The key exists but the remaining survival time is not set. Return-1.

Persist key cancels expiration time

Select dbindex selects databases. There are 16 databases by default, and the index starts at 0.

Move key, dbindex moves key from the current database to the dbindex database

Randomkey randomly returns a key

Keyrename key, key2 renamed key

Dbsize returns the number of key in the current database

Info view database information

Config get * stores the received requests in real time and returns the relevant configuration

Type of value returned by type (key)

Flushdb deletes all key in the currently selected database

Flushall deletes all key from all databases

1. String String

String is the most basic type of redis. A key can store 523MB as much as possible. The String type is binary safe. It means that the String of redis can contain any data. Such as pictures or serialized objects.

Application scenarios of String:

String is typically used to save a single string or JSON string data.

Because String is binary secure, the contents of the image file can be stored as strings.

Counter (regular key-value cache application, number of fans, number of Weibo, voting, etc.)

INCR and other instructions have the characteristics of atomic operation, so we can use Redis's NCR, INCRBY, DECR, DECRBY and other instructions to achieve the effect of atomic counting. If, in some scenario, three clients read the value of minum at the same time (the value is 2), and then add 1 to it at the same time, then the final value of bynum must be 5. Many websites use this feature of reds to achieve business statistical counting requirements.

Assignment grammar

Set key value assigns the value value to key. Multiple settings will overwrite the old value and ignore the type.

Setnx key value assigns the value value to key, and if key already exists, it does not set and returns 0, otherwise it sets and returns 1. It is one of the solutions to solve distributed locks.

Setex key time value assigns the value value to key and sets the expiration time time. Both key and value are cleared after expiration.

Setrange key start end sets the value within the specified range, with the subscript starting at 0 and replacing the string.

Value syntax

Get key gets the value of the specified key. If key does not exist, nil is returned.

Getrange key start end gets the substrings of the value of the specified key, including start and end corner marks

Getbit key offset gets the bit (binary) of the specified offset from the string value stored in key

Getset key value sets a new value for key and returns the old value. There is no return nil for key.

Substr (key, start, end) returns the substring of the value of string named key

Delete value syntax

Del key is the same as Key

Batch write

Mset K1 v1 K2 v2...kn vn sets multiple values in batches

Batch readout

Mget k1 k2... Kn gets the values of multiple key

Increase and decrease

Value correspondence of incr key key + 1

Value correspondence of incrby key integer key + integer

The value correspondence of decr key key is-1

Value correspondence of decrby key integer key-integer

String concatenation

Append key value appends value to the end of the specified key

Msetnx (key1, value1...keyN, valueN) sets multiple key and value at the same time, only if key does not exist before.

String length

Strlen key returns the character length of key

Second, double bond value pair Hash

The Hash type is a mapping table for field and value of type String. Hash is particularly suitable for storing objects, takes up less disk space than String, and can be seen as a map container with key and value. Each hash in Redis can store (2 ^ 32)-1 key-value pair.

Application scenarios of Hash:

It is usually used to store a user information object data.

Redis's Hash actually uses the internally stored value as a HashMap.

Assignment grammar

Hset key field value sets field and value for the specified key

Hsetnx key field value sets field and value for the specified key, and does not take effect if key already exists.

Hmset key f1 v1 f2 v2... Fn vn simultaneously sets multiple field-value (field value pairs) to the key of the hash table.

Value syntax

Hget key field acquires the value based on field

Hmget key f1 f2... Fn acquires all values based on multiple field

Hgetall key gets all the fields and values in the Hash table

Hkeys key gets all the fields in the Hash table

Hvals key gets the value corresponding to all the fields in the Hash table

Hexists key field checks whether the specified field exists in the Hash table Key

Hlen key gets the number of fields in the Hash table

Delete syntax

Hdel key field1 field2... Fieldn deletes fields from one or more Hash tables

Del key is the same as Key

Addition and subtraction grammar

Hincrby key field integer adds integer to the value corresponding to field in Hash table Key

Hincrbyfloat key field increment adds increment to the value corresponding to field in Hash table Key

3. Double-ended linked list List

The List type is a collection of linked list structures, and its main functions are push, pop, getting elements, and so on. In more detail, the List type is a double-ended linked list structure, which can add and delete the header or tail elements of the collection through related operations. List can be used as both a stack and a queue to meet most of the needs.

If the key does not exist, create a new linked list.

If the key already exists, add something.

If all values are removed, the corresponding key disappears.

The efficiency of linked list operation is very high in both head and tail, but the operation efficiency of intermediate elements is very low.

Application scenario

Delete the collection data with a large amount of data

List data display, follow list, fan list, message comments, etc. Paging, hot news (Top10), etc. The function of paging can be easily realized by using lrange. In the blog system, the comments of each blog post can also be stored in a separate list.

Task queue

When processing command requests sent by the web client, some operations may take longer than we expected. By putting information about the tasks to be executed in the queue, and then processing the queue later, users can postpone the execution of those operations that take a while to complete. This practice of handing the work to the task processor is called the task queue (task queue). List can usually be used to implement a message queue and to ensure sequencing.

Assignment grammar

Lpush key value1 value2... ValueN inserts one or more values into the list header (added from the left)

Rpush key value1 value2... ValueN inserts one or more values into the list header (add from the right)

Lpushx key value inserts a value into the existing list header (leftmost). If the list does not exist, the operation is invalid.

Rpushx key value inserts a value at the end of the existing list (rightmost). If the list does not exist, the operation is invalid.

Value syntax

Llen key gets the list length

Lindex key index gets the elements of the list through the index

Lrange key start stop gets elements within the specified range of the list

Delete syntax

Lpop key removes and gets the first element of the list (removed from the left)

Lpop key removes and gets the last element of the list (removed from the right)

Lrem key count value deletes key with the value of count value

Blpop key1 key2 timeout removes and fetches the first element of the list, blocking the list if there are no elements in the list until waiting for a timeout or until a popup element is found

Brpop key1 key2 timeout removes and gets the last element of the list, blocking the list if there are no elements in the list until waiting for a timeout or until a popup element is found

Ltrim key start stop prunes a list, keeping only the elements within the specified range, and deleting all elements that are not within the specified range.

Modify syntax

Lset key index value sets the value of the list element through the index

Linsert key before | after world value inserts the element value before or after an element world in the list.

Advanced command

Rpoplpush source destination removes the last element of the source list, adds it to the destination list, and returns. (you can operate on yourself, like a queue)

Brpoplpush source destination timeout removes the last element of the source list, adds it to the destination list, and returns; if there is no element in the source list, it blocks the list until the wait times out or until it is found that the element can be removed.

4. Unordered set Set

Set is an unordered collection of type String. Collection members are unique and there can be no duplicate data in the collection.

The collection in Redis is implemented through a hash table, so the complexity of adding, deleting, and searching is O (1).

The maximum number of members in the collection is 4294967295 (each collection can store more than 4 billion members).

Similar to the Hashtable collection in JAVA

The underlying storage structure of Redis's set is particularly magical. The underlying storage uses two data structures, intset and hashtable. Intset can be understood as an array, and hashtable is an ordinary hash table (key is the value of set and value is null).

Intset is actually an array (int8_t coentents [] array), and the data is stored in order, because it is done by binary lookup when looking up the data.

Application scenario

Perform intersection, union and subtraction operations on the data [calculation] between two sets

It is very convenient to achieve functions such as common concern, common preferences, second friends and so on. For all of the above collection operations, you can also use different commands to choose whether to return the results to the client or store them in a new collection.

Using uniqueness, you can count all the independent IP that visit the website

Assignment grammar

Sadd key member1 member2... MemberN adds one or more members to the collection

Value syntax

Scard key gets the number of members of the collection

Smembers key returns all members of the collection

Sismember key member determines whether the member element is a member of the collection key (in development: verifying whether there is a judgment)

Srandmember key count returns one or more random numbers in the collection

Delete syntax

Srem key member1 member2...memberN removes one or more members from the collection

Spop kye count removes and returns one or more random elements in the collection

Smove source destincation member moves member elements from the source collection to the destination collection

Subtraction grammar

Sdiff key1 key2 returns the difference of all given sets (left)

Sdiffstore destination key1 key2 returns the difference of all given sets and stores them in destination (original data cleanup in destination)

Intersection grammar

Sinter key1 key2 returns the intersection of all given sets (common data)

Sinterstore destination key1 key2 returns the intersection of all given collections and stores them in destination

Union grammar

Sunion key1 key2 returns the union of all given sets

Sunionstore destination key1 key2 the union of all given collections is stored in the destination collection

5. Ordered set Zset

Redis zset, like set, is a collection of elements of type string, and duplicate members are not allowed. The difference is that each element is associated with a score of type double. Redis sorts the members of the collection from small to large by scores. The members of the zset are unique, but the score can be repeated.

The previous set was K1 v1 v2

Now the zset is K1 score1 v1 score2 v2

Application scenario

Ranking

The public timeline of ① twitter can be stored as the score of the publication time, so that the acquisition is automatically sorted according to time.

② A Sorted Set that stores the scores of the whole class. The collection value can be the student number of the classmate, and the score can be the test score, so that the data is naturally sorted when the data is inserted into the collection.

③ uses Sorted Set to make weighted queues, such as score of normal messages is 1, score of important messages is 2, and worker threads can choose to get work tasks in reverse order of score. Give priority to important tasks.

Assignment grammar

Zadd key score1 member1 score2 member2 adds one or more members to an ordered collection, or updates the scores of existing members

Value syntax

Zcard key gets the number of members of an ordered set

Zcount key min max calculates the number of members with a specified interval score in an ordered set

Zrank key member returns the index of the specified member in an ordered collection

Zrange key start stop [withscores] synthesizes the members of a specified interval (low to high) by returning an ordered set of index intervals

Zrevrange key start stop [withscores] synthesizes the members of a specified interval (high to low) by returning an ordered set of index intervals

Zlexcount key,min,max calculates the number of members in a specified dictionary interval in an ordered set

Delete syntax

Del key removes a collection

Zrem key member [member...] removes one or more members from an ordered collection

Zremrangebyrank key start stop removes all members of a given ranking interval in an ordered set (first place is 0) (low to high sort)

Zremrangebyscore key min max removes all members of a given fraction interval in an ordered set

Score self-increasing

Add an incremental increment to the score of a specified member in an zincrby key ncrement member ordered set

VI. HyperLoglog

Redis added the HyperLoglog structure in version 2.8.9. This structure is used to do cardinality statistics algorithm.

Advantages: no matter how many input elements, the space needed to calculate the cardinality is always fixed and small.

Disadvantages: the cardinality is only calculated based on the input element, not the input element itself, and the index cannot return each input element like the collection.

What is the cardinality?

For example, if the dataset {1pyrrine 2rec 3rec 3je 4je 5je 5}, then the cardinality set of this dataset is {1pr 2pm 3pm 4je 5}, and the cardinality is 5. The so-called cardinality estimation is to quickly calculate the cardinality within the acceptable range of error.

Why use HyperLogLog?

Traditionally, the base value of an object needs 12 MB of memory. If you count 10, 000 objects, it requires nearly 120 GB of memory, which can not be widely used in big data scenes. However, using HyperLogLog to calculate the base value of 100 million pieces of data, it takes about 12 MB, and the memory footprint is significantly reduced.

Pfadd key element1 element2... ElementN adds the specified element to the HyperLogLog

Pfcount key returns the cardinality estimate of the given HyperLogLog

Pfmerge destkey sourcekey1 sourcekey2. SourcekeyN combines multiple HyperLogLog into a single HyperLogLog

This is the end of this article on "what are the operating instructions for common data types in Redis?". I hope the above content can be helpful to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Database

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report