Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Redis HyperLogLog

Redis HyperLogLog

Redis added the HyperLogLog structure in version 2.8.9.

Redis HyperLogLog is an algorithm for cardinality statistics. Its advantage is that when the number or volume of input elements is very large, the space required to compute the cardinality is always fixed and very small.

In Redis, each HyperLogLog key only needs 12 KB of memory to compute the cardinality of nearly 2^64 different elements. This is in sharp contrast to sets, where the more elements, the more memory is consumed.

However, because HyperLogLog only computes the cardinality based on input elements and does not store the input elements themselves, it cannot, like a set, return the individual input elements.


What is cardinality?

For example, for the data set {1, 3, 5, 7, 5, 7, 8}, the cardinality set is {1, 3, 5, 7, 8}, and the cardinality (number of unique elements) is 5. Cardinality estimation is the fast computation of cardinality within an acceptable error range.


Example

The following example demonstrates the working process of HyperLogLog:



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


Redis HyperLogLog Commands

The table below lists the basic redis HyperLogLog commands:

No. Command and Description
1 PFADD key element [element ...]
Add the specified element to the HyperLogLog.
2 PFCOUNT key [key ...]
Return the cardinality estimate of the given HyperLogLog.
3 PFMERGE destkey sourcekey [sourcekey ...]
Merge multiple HyperLogLogs into one HyperLogLog