Table of Contents
sorted set ordered set" >sorted set ordered set
slightly" >hash Hash slightly
Home PHP Framework Laravel Understand the core data type of Redis

Understand the core data type of Redis

Jul 03, 2020 pm 05:20 PM
laravel redis

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 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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Laravel - Artisan Commands Laravel - Artisan Commands Aug 27, 2024 am 10:51 AM

Laravel - Artisan Commands - Laravel 5.7 comes with new way of treating and testing new commands. It includes a new feature of testing artisan commands and the demonstration is mentioned below ?

Laravel - Artisan Console Laravel - Artisan Console Aug 27, 2024 am 10:51 AM

Laravel - Artisan Console - Laravel framework provides three primary tools for interaction through command-line namely: Artisan, Ticker and REPL. This chapter explains about Artisan in detail.

Laravel - Pagination Customizations Laravel - Pagination Customizations Aug 27, 2024 am 10:51 AM

Laravel - Pagination Customizations - Laravel includes a feature of pagination which helps a user or a developer to include a pagination feature. Laravel paginator is integrated with the query builder and Eloquent ORM. The paginate method automatical

Why does an error occur when installing an extension using PECL in a Docker environment? How to solve it? Why does an error occur when installing an extension using PECL in a Docker environment? How to solve it? Apr 01, 2025 pm 03:06 PM

Causes and solutions for errors when using PECL to install extensions in Docker environment When using Docker environment, we often encounter some headaches...

Laravel - Dump Server Laravel - Dump Server Aug 27, 2024 am 10:51 AM

Laravel - Dump Server - Laravel dump server comes with the version of Laravel 5.7. The previous versions do not include any dump server. Dump server will be a development dependency in laravel/laravel composer file.

Laravel - Facades Laravel - Facades Aug 27, 2024 am 10:50 AM

Laravel - Facades - Facades provide a static interface to classes that are available in the application's service container. Laravel facades serve as static proxies to underlying classes in the service container, providing the benefit of a terse, exp

In Laravel, how to deal with the situation where verification codes are failed to be sent by email? In Laravel, how to deal with the situation where verification codes are failed to be sent by email? Mar 31, 2025 pm 11:48 PM

The method of handling Laravel's email failure to send verification code is to use Laravel...

Laravel - Sending Email Laravel - Sending Email Aug 27, 2024 am 10:50 AM

Laravel - Sending Email - Laravel uses free feature-rich library SwiftMailer to send emails. Using the library function, we can easily send emails without too many hassles. The e-mail templates are loaded in the same way as views, which means you can

See all articles