Redis added the HyperLogLog structure in version 2.8.9.

Redis HyperLogLog is used to do cardinality statistics algorithm. The advantage of HyperLogLog is that when the number or volume of input elements is very, very large, the space required to calculate the cardinality is always fixed and small.

In Redis, each HyperLogLog key costs only 12 KB of memory to calculate the bases of close to 2^64 different elements. This is in stark contrast to collections where the more elements you have, the more memory you consume when calculating cardinality.

However, because HyperLogLog only calculates the cardinality from the input elements and does not store the input elements themselves, HyperLogLog cannot return the individual elements of the input, as collections do.

What is the cardinal number?

For example, a dataset {1, 3, 5, 7, 5, 7, 8} would have a cardinality of {1, 3, 5, 7, 8} and a cardinality (not repeating elements) of 5. Cardinality estimation is to quickly calculate the cardinality within an acceptable range of error.

The instance

The following example shows how HyperLogLog works:

Redis 127.0.0.1:6379> PFADD runoobkey "redis" 1) (integer) 1 redis 127.0.0.1:6379> PFADD runoobkey "mongodb" 1) (integer) 1 redis 127.0.0.1:6379> PFADD runoobkey "mysql" 1) (integer) 1 redis 127.0.0.1:6379> PFCOUNT runoobkey (integer) 3Copy the code

Redis HyperLogLog command

The following table lists the basic commands for Redis HyperLogLog:

The serial number

Commands and Description

1

PFADD key element [element …] Adds the specified element to HyperLogLog.

2

PFCOUNT key [key …] Returns the cardinality estimate for the given HyperLogLog.

3

PFMERGE destkey sourcekey [sourcekey …] Merge multiple Hyperloglogs into one HyperLogLog

———————————-

Redis PFMERGE command

The Redis PFMERGE command merges multiple HyperLogLog into one HyperLogLog. The cardinality estimate of the combined HyperLogLog is calculated by combining all the given HyperLogLog.

grammar

The syntax of the redis PFMERGE command is as follows:

PFMERGE destkey sourcekey [sourcekey ...]
Copy the code

Version available

> = 2.8.9

The return value

Return OK.

The instance

redis> PFADD hll1 foo bar zap a
(integer) 1
redis> PFADD hll2 a b c foo
(integer) 1
redis> PFMERGE hll3 hll1 hll2
"OK"
redis> PFCOUNT hll3
(integer) 6
redis>  
Copy the code

end