search
HomePHP FrameworkLaravelUnderstand the core data type of Redis

Understand the core data type of Redis

Jul 03, 2020 pm 05:20 PM
laravelredis

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. If there is any infringement, please contact admin@php.cn delete
Laravel's Impact: Simplifying Web DevelopmentLaravel's Impact: Simplifying Web DevelopmentApr 21, 2025 am 12:18 AM

Laravel stands out by simplifying the web development process and delivering powerful features. Its advantages include: 1) concise syntax and powerful ORM system, 2) efficient routing and authentication system, 3) rich third-party library support, allowing developers to focus on writing elegant code and improve development efficiency.

Laravel: Frontend or Backend? Clarifying the Framework's RoleLaravel: Frontend or Backend? Clarifying the Framework's RoleApr 21, 2025 am 12:17 AM

Laravelispredominantlyabackendframework,designedforserver-sidelogic,databasemanagement,andAPIdevelopment,thoughitalsosupportsfrontenddevelopmentwithBladetemplates.

Laravel vs. Python: Exploring Performance and ScalabilityLaravel vs. Python: Exploring Performance and ScalabilityApr 21, 2025 am 12:16 AM

Laravel and Python have their own advantages and disadvantages in terms of performance and scalability. Laravel improves performance through asynchronous processing and queueing systems, but due to PHP limitations, there may be bottlenecks when high concurrency is present; Python performs well with the asynchronous framework and a powerful library ecosystem, but is affected by GIL in a multi-threaded environment.

Laravel vs. Python (with Frameworks): A Comparative AnalysisLaravel vs. Python (with Frameworks): A Comparative AnalysisApr 21, 2025 am 12:15 AM

Laravel is suitable for projects that teams are familiar with PHP and require rich features, while Python frameworks depend on project requirements. 1.Laravel provides elegant syntax and rich features, suitable for projects that require rapid development and flexibility. 2. Django is suitable for complex applications because of its "battery inclusion" concept. 3.Flask is suitable for fast prototypes and small projects, providing great flexibility.

Frontend with Laravel: Exploring the PossibilitiesFrontend with Laravel: Exploring the PossibilitiesApr 20, 2025 am 12:19 AM

Laravel can be used for front-end development. 1) Use the Blade template engine to generate HTML. 2) Integrate Vite to manage front-end resources. 3) Build SPA, PWA or static website. 4) Combine routing, middleware and EloquentORM to create a complete web application.

PHP and Laravel: Building Server-Side ApplicationsPHP and Laravel: Building Server-Side ApplicationsApr 20, 2025 am 12:17 AM

PHP and Laravel can be used to build efficient server-side applications. 1.PHP is an open source scripting language suitable for web development. 2.Laravel provides routing, controller, EloquentORM, Blade template engine and other functions to simplify development. 3. Improve application performance and security through caching, code optimization and security measures. 4. Test and deployment strategies to ensure stable operation of applications.

Laravel vs. Python: The Learning Curves and Ease of UseLaravel vs. Python: The Learning Curves and Ease of UseApr 20, 2025 am 12:17 AM

Laravel and Python have their own advantages and disadvantages in terms of learning curve and ease of use. Laravel is suitable for rapid development of web applications. The learning curve is relatively flat, but it takes time to master advanced functions. Python's grammar is concise and the learning curve is flat, but dynamic type systems need to be cautious.

Laravel's Strengths: Backend DevelopmentLaravel's Strengths: Backend DevelopmentApr 20, 2025 am 12:16 AM

Laravel's advantages in back-end development include: 1) elegant syntax and EloquentORM simplify the development process; 2) rich ecosystem and active community support; 3) improved development efficiency and code quality. Laravel's design allows developers to develop more efficiently and improve code quality through its powerful features and tools.

See all articles

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

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools