search
HomeDatabaseRedisHow to use Redis's HyperLogLog algorithm

How to use Redis's HyperLogLog algorithm

May 29, 2023 pm 09:49 PM
redishyperloglog

How to use Rediss HyperLogLog algorithm

You are happily slacking off, but the product manager sends you a requirements document via email. The company needs to keep long-term statistics on the website's daily visitor IPs, and the statistical time may last for months or even years.

After reading the requirements, you will feel that this is so easy. You can easily implement this function using the collection type of Redis: generate a collection type key every day, use SADD to store the daily visitor IP, and use the SCARD command to easily Get the number of visitor IPs per day.

You quickly finished typing the code and passed the test, and the function was online. After going online and running for a period of time, you will find that the server where Redis is located starts to alarm. The reason is that the memory usage of some keys is too large. You took a look and found that these keys are all set keys that store visitor IPs. Only then did you pat your head, knowing that you had dug a big hole for yourself.

Assume that storing an IP address in IPv4 format requires up to 15 bytes and that the website has up to 1 million visitors per day. These collection keys will use 0.45 GB of memory per month and 5.4 GB of memory per year. This is only an estimate of the IPv4 format. If the IPv6 format will occupy more memory. Although the time complexity of SADD and SCARD is O(1), their memory consumption is intolerable.

You browsed the official website of Redis and found that Redis also provides a data type HyperLogLog, which can not only meet the needs of the product but also occupy less memory.

HyperLogLog Algorithm

HyperLogLog is a probabilistic algorithm created specifically for calculating the cardinality of a set. It can calculate the approximate cardinality of a given set.

The approximate cardinality is not the actual cardinality of the set. It may be a little smaller or larger than the actual cardinality, but the error between the estimated cardinality and the actual cardinality will be within a reasonable range. For those who do not require Very accurate statistics can be achieved using the HyperLogLog algorithm.

The advantage of HyperLogLog is that the memory required for calculating the approximate cardinality does not change due to the size of the set. No matter how many elements the set contains, the memory required for HyperLogLog to calculate is always fixed, and are very few.

Each HyperLogLog type of Redis only needs to use 12KB of memory space to count nearly: 264 elements, and the standard error of the algorithm is only 0.81%.

If you use the HyperLogLog type to implement the above functions, if there are 1 million visitors per day, it will only occupy 360KB of memory in one month.

PFADD

The PFADD command can be used to count one or more given set elements.

PFADD key element [element...]

Depending on whether the given element has been counted, the PFADD command may return 0 or 1:

  • If all the given elements have been counted, the PFADD command will return 0, indicating that the approximate cardinality calculated by HyperLogLog has not changed.

  • The PFADD command will return 1 if the approximate cardinality calculated by HyperLogLog changes due to the presence of at least one element in a given element that has not been previously counted.

For example:

redis> PFADD letters a b c -- 第一次添加
(integer) 1
redis> PFADD letters a     -- 第二次添加
(integer) 0

It is also possible if you only specify the key without specifying the element when calling this command. If the key exists, no operation will be performed. If If it does not exist, a data structure will be created (returns 1).

PFCOUNT

Use the PFCOUNT command to obtain the set cardinality based on HyperLogLog approximate calculation. If the given key does not exist, 0 will be returned.

PFCOUNT key [key...]

For example:

redis> PFCOUNT letters
(integer) 3

When multiple HyperLogLogs are passed to PFCOUNT, the PFCOUNT command will first The union of all HyperLogLogs is then returned and the approximate cardinality is returned.

redis> PFADD letters1 a b c
(integer) 1
redis> PFADD letters2 c d e
(integer) 1
redis> PFCOUNT letters1 letters2
(integer) 5

PFMERGE

The PFMERGE command can perform a union calculation on multiple HyperLogLogs, and then save the calculated union HyperLogLog to the specified key.

PFMERGE destKey sourceKey [sourceKey...]

If the specified key already exists, the PFMERGE command will overwrite the existing key.

redis> PFADD letters1 a b c
(integer) 1
redis> PFADD letters2 c d e
(integer) 1
redis> PFMERGE res letters1 letters2
OK
redis> PFCOUNT res
(integer) 5

You can see that the PFMERGE and PFCOUNT commands are very similar. In fact, the PFCOUNT command performs the following operations when calculating the approximate base of multiple HyperLogLogs:

  • Internally called The PFMERGE command calculates the union of all given HyperLogLogs and stores the union into a temporary HyperLogLog.

  • Execute the PFCOUNT command on the temporary HyperLogLog to get its approximate cardinality.

  • Delete the temporary HyperLogLog.

  • Return the resulting approximate base.

When the program needs to call the PFCOUNT command on multiple HyperLogLogs, and this call may be repeated multiple times, you can consider replacing this call with the corresponding PFMERGE command call: by combining the The calculation results are stored in the specified HyperLogLog instead of recalculating the union every time, and the program can minimize unnecessary union calculations.

Business Scenario

HyperLogLog’s features are very suitable for: counting (monthly, annual statistics), deduplication (spam SMS detection) and other scenarios.

The above is the detailed content of How to use Redis's HyperLogLog algorithm. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
Redis: Classifying Its Database ApproachRedis: Classifying Its Database ApproachApr 15, 2025 am 12:06 AM

Redis's database methods include in-memory databases and key-value storage. 1) Redis stores data in memory, and reads and writes fast. 2) It uses key-value pairs to store data, supports complex data structures such as lists, collections, hash tables and ordered collections, suitable for caches and NoSQL databases.

Why Use Redis? Benefits and AdvantagesWhy Use Redis? Benefits and AdvantagesApr 14, 2025 am 12:07 AM

Redis is a powerful database solution because it provides fast performance, rich data structures, high availability and scalability, persistence capabilities, and a wide range of ecosystem support. 1) Extremely fast performance: Redis's data is stored in memory and has extremely fast read and write speeds, suitable for high concurrency and low latency applications. 2) Rich data structure: supports multiple data types, such as lists, collections, etc., which are suitable for a variety of scenarios. 3) High availability and scalability: supports master-slave replication and cluster mode to achieve high availability and horizontal scalability. 4) Persistence and data security: Data persistence is achieved through RDB and AOF to ensure data integrity and reliability. 5) Wide ecosystem and community support: with a huge ecosystem and active community,

Understanding NoSQL: Key Features of RedisUnderstanding NoSQL: Key Features of RedisApr 13, 2025 am 12:17 AM

Key features of Redis include speed, flexibility and rich data structure support. 1) Speed: Redis is an in-memory database, and read and write operations are almost instantaneous, suitable for cache and session management. 2) Flexibility: Supports multiple data structures, such as strings, lists, collections, etc., which are suitable for complex data processing. 3) Data structure support: provides strings, lists, collections, hash tables, etc., which are suitable for different business needs.

Redis: Identifying Its Primary FunctionRedis: Identifying Its Primary FunctionApr 12, 2025 am 12:01 AM

The core function of Redis is a high-performance in-memory data storage and processing system. 1) High-speed data access: Redis stores data in memory and provides microsecond-level read and write speed. 2) Rich data structure: supports strings, lists, collections, etc., and adapts to a variety of application scenarios. 3) Persistence: Persist data to disk through RDB and AOF. 4) Publish subscription: Can be used in message queues or real-time communication systems.

Redis: A Guide to Popular Data StructuresRedis: A Guide to Popular Data StructuresApr 11, 2025 am 12:04 AM

Redis supports a variety of data structures, including: 1. String, suitable for storing single-value data; 2. List, suitable for queues and stacks; 3. Set, used for storing non-duplicate data; 4. Ordered Set, suitable for ranking lists and priority queues; 5. Hash table, suitable for storing object or structured data.

How to implement redis counterHow to implement redis counterApr 10, 2025 pm 10:21 PM

Redis counter is a mechanism that uses Redis key-value pair storage to implement counting operations, including the following steps: creating counter keys, increasing counts, decreasing counts, resetting counts, and obtaining counts. The advantages of Redis counters include fast speed, high concurrency, durability and simplicity and ease of use. It can be used in scenarios such as user access counting, real-time metric tracking, game scores and rankings, and order processing counting.

How to use the redis command lineHow to use the redis command lineApr 10, 2025 pm 10:18 PM

Use the Redis command line tool (redis-cli) to manage and operate Redis through the following steps: Connect to the server, specify the address and port. Send commands to the server using the command name and parameters. Use the HELP command to view help information for a specific command. Use the QUIT command to exit the command line tool.

How to build the redis cluster modeHow to build the redis cluster modeApr 10, 2025 pm 10:15 PM

Redis cluster mode deploys Redis instances to multiple servers through sharding, improving scalability and availability. The construction steps are as follows: Create odd Redis instances with different ports; Create 3 sentinel instances, monitor Redis instances and failover; configure sentinel configuration files, add monitoring Redis instance information and failover settings; configure Redis instance configuration files, enable cluster mode and specify the cluster information file path; create nodes.conf file, containing information of each Redis instance; start the cluster, execute the create command to create a cluster and specify the number of replicas; log in to the cluster to execute the CLUSTER INFO command to verify the cluster status; make

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

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)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool