Home  >  Article  >  PHP Framework  >  Understand the core data type of Redis

Understand the core data type of Redis

coldplay.xixi
coldplay.xixiforward
2020-07-03 17:20:102713browse

Understand the core data type of Redis

string The string

tring type is binary safe, i.e. string can contain any data.

Ordinary strings in Redis use raw encoding, which is the original encoding method. This encoding method will dynamically expand and pre-allocate redundant space in advance to reduce the overhead of frequent memory allocation.

When the string length is less than 1MB, it will be allocated at twice the required length. If it exceeds 1MB, it will be pre-allocated by increasing the capacity by 1MB each time. The numbers in

Redis are also stored as string types, but the encoding method is different from ordinary strings. The numbers use integer encoding, and the string content is directly set to Binary byte sequence of integer values.

When storing ordinary strings, serialized objects, counters and other scenarios, you can use the Redis string type. The instructions corresponding to the string data type include set, get, mset, incr, decr, etc. .

list list

list The list is a fast two-way linked list that stores a series of string type words String value

For conventional pop and push elements, the performance is very high, and the time complexity is O(1), because the list is directly appended or popped. However, for random insertion, random deletion, and random range acquisition, the position needs to be determined by polling the list, and the performance is relatively low.

When operating the list, you can use lpush, lpop, rpush, rpop, and lrange to perform regular queue entry and exit and range acquisition operations. In some special scenarios, you can also use lset and linsert to perform random insertion operations. , use lrem to perform the specified element deletion operation; finally, when consuming the message list, you can also use Blpop and Brpop for blocking acquisition, so that when the list temporarily has no elements, you can quietly wait for the insertion of new elements without additional Continuous inquiry.

set Set

set is an unordered collection of string type. The elements in the set are unique, that is, there will be no duplicate elements in the set. Collections in Redis are generally implemented through dict hash tables, so insertion, deletion, and query elements can be directly located based on the hash value of the element, and the time complexity is O(1).

Operation

  • sismember The instruction determines whether there is an element in the set data structure corresponding to the key. If Returns 1 if exists, otherwise returns 0;

  • sdiff instruction to perform differences on multiple set collections;

  • sinter The instruction performs intersection on multiple sets;

  • sunion The instruction performs union on multiple sets;

  • # The
  • ##spop command pops up a random element; the

  • srandmember command returns one or more random elements.

In the social system, it can be used to store the

friend list that you follow, to determine whether you are paying attention, and to make friend recommendations. In addition, you can also use the uniqueness of set to make accurate statistics on the source business and source IP of the service.

sorted set ordered set

In an ordered set, each element is associated with a double type score value. The sorted set is sorted from small to large by this score value. In an ordered set, elements are not allowed to be repeated, but score values ​​are allowed to be repeated.

Operation

  • ##zscan

    Instruction: Get the elements in the ordered set in order;

  • zscore

    Instruction: Get the score value of the element;

  • zrange

    Instruction: Return the specified score range by specifying the score element;

  • When the score value of an element changes, you can also add or subtract the score value of the element through the zincrby instruction.
  • Use
  • zinterstore, zunionstore

    instructions to intersect and union multiple ordered sets, and then store the new ordered set in a new key , if there are duplicate elements, the scores of the duplicate elements are added, and then used as the score value of the element in the new set.

  • You can use ordered collections to count rankings and refresh the rankings in real time. It can also be used to record student scores, thereby easily obtaining a list of students within a certain score range. You can also use To add weight to system statistics and display them in real time on the dashboard.

hash Hash slightly

bitmap

A bitmap is a series of continuous binary numbers. The bottom layer is actually encapsulated and stored based on string

by bit Perform command operations. The position of each bit in the bitmap is the offset. You can use setbit and bitfield to set each bit in the bitmap to 0 or 1. You can also use bitcount to count the number of bits set to 1 in the bitmap. You can also use bitcount to count the number of bits set to 1 in the bitmap. Bitop can be used to perform operations such as AND, OR, XOR, etc. on multiple bitmaps.

Redis 笔记

bitmap The characteristic of bitmap is that operations such as bitwise setting, summing, and ORing are very efficient, and the storage cost is very low. It is used to store For object label attributes, one bit can store a label. You can use bitmap to store the user's login status in the last N days, using 1 bit every day, and setting it to 1 when logging in.

Personalized recommendation is very important in social applications. You can set a series of tags for news and feeds, such as military, entertainment, video, pictures, text, etc. Bitmap is used to store these tags, and the corresponding tag bits are Set to 1. For users, a similar method can be used to record multiple attributes of users, and multi-dimensional statistics can be easily performed based on tags. Important instructions for bitmap bitmaps include: setbit, getbit, bitcount, bitfield, bitop, bitpos, etc.

Usage experience

Statistical user login status: 1 2 3 Login within 5 days
bitmap: 1 1 1 0 1

GEO Geographical Location

When storing a certain location point, first use the Geohash algorithm to map and encode the two-dimensional longitude and latitude of the location into a one-dimensional 52-bit integer value. The location name and longitude and latitude encoding score are used as key-value pairs and stored in the sorted set corresponding to the classification key.

When you need to calculate the people near a certain location point A, first use the specified location A as the center point and the distance as the radius to calculate the 8-azimuth range of the GEO hash, and then poll the people within the azimuth range in sequence. All position points, as long as the distance between these position points and the center position A is within the required distance range, is the target position point. After polling all location points within the range, reorder to obtain all targets near location point A.

Use geoadd to add location names (such as people, vehicles, store names) and corresponding geographical location information to the specified location classification key;

Use geopos to easily query the location of a certain name Location information;

Use georadius to obtain all elements near the specified location and not exceeding the specified distance;

Redis GEO geographical location, use Geohash to convert a large number of two-dimensional longitude and latitude into one-dimensional integer values , which makes it easy to query geographical location, measure distance, and search range. However, due to the large number of geographical points, there may be a large number of elements under one geographical classification key. When designing GEO, it is necessary to plan in advance to avoid excessive expansion of a single key.

Redis's GEO geographical location data structure has many application scenarios, such as querying the specific location of a place, checking the distance from the current location to the destination, and checking nearby people, restaurants, movie theaters, etc. In the GEO geographical location data structure, important instructions include geoadd, geopos, geodist, georadius, georadiusbymember, etc.

Use geodist to get the distance between two specified locations.

hyperLogLog Cardinality statistics

hyperLogLog is a data type used for cardinality statistics. When a huge number of elements are input for statistics, only It can be done with very little memory. HyperLogLog does not save metadata, but only records the estimated number of elements to be counted. This estimated number is an approximation with a standard deviation of 0.81%. In most business scenarios, for massive data, an error of less than 1% is acceptable.

When counting the HyperLogLog of Redis, if the number of counts is not large, sparse matrix storage is used. As the count increases, the space occupied by the sparse matrix will gradually increase. When the threshold is exceeded, it will be changed to dense. Matrix, the space occupied by dense matrix is ​​fixed, about 12KB bytes.

Through the hyperLoglog data type, you can use pfadd to add new elements to the cardinality statistics, you can use pfcount to obtain the approximate cardinality number stored in the hyperLogLog structure, and you can also use hypermerge to merge multiple hyperLogLogs into one hyperLogLog structure. , so that the combined base number can be easily obtained.

The characteristic of hyperLogLog is that the statistical process does not record independent elements, takes up very little memory, and is very suitable for counting massive data. In large and medium-sized systems, the hyperLogLog data type can be used to count the number of unique visitors per day or month, or to count the number of independent terms searched by a large number of users.

Related learning recommendations: Laravel

The above is the detailed content of Understand the core data type of Redis. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:learnku.com. If there is any infringement, please contact admin@php.cn delete