The Redis PFMERGE command merges multiple HyperLogLogs into a single HyperLogLog. The cardinality estimate of the resulting HyperLogLog is calculated by taking the union of all the given HyperLogLogs.

Syntax

The basic syntax of the PFMERGE command is as follows:

1
PFMERGE destkey [sourcekey [sourcekey ...]]

The command merges multiple HyperLogLog values to approximate the cardinality of the union of the observed sets. The result is stored in a destination variable, which is created if it doesn’t already exist (defaulting to an empty HyperLogLog). If the destination variable already exists, it is treated as one of the source sets, and its cardinality is included in the final merged HyperLogLog.

Available Since

Version 2.8.9 or later.

Time Complexity

O(N) to merge N HyperLogLogs, but with high constant times.

ACL Categories

@write, @hyperloglog, @slow

Return Value

Returns OK.

Example 1

Merge two HyperLogLogs into one and store it under a non-existing key:

1
2
3
4
5
6
7
8
127.0.0.1:6379> PFADD hll:1 a b c
(integer) 1
127.0.0.1:6379> PFADD "hll:2" d e f
(integer) 1
127.0.0.1:6379> PFMERGE "hll:target" "hll:1" "hll:2"
OK
127.0.0.1:6379> PFCOUNT "hll:target"
(integer) 6

Example 2

Merge two HyperLogLogs into one and store it under an existing key:

1
2
3
4
5
6
7
8
9
10
127.0.0.1:6379> PFADD hll:1 a b c
(integer) 1
127.0.0.1:6379> PFADD "hll:2" d e f
(integer) 1
127.0.0.1:6379> PFADD "hll:3" z
(integer) 1
127.0.0.1:6379> PFMERGE "hll:3" "hll:1" "hll:2"
OK
127.0.0.1:6379> PFCOUNT "hll:3"
(integer) 7

Example 3

If you attempt to merge two HyperLogLogs into one and store the result under an existing key where the value type is a string, Redis will throw the following exception:

1
(error) WRONGTYPE Key is not a valid HyperLogLog string value.

The following example illustrates this scenario:

1
2
3
4
5
6
7
8
9
10
127.0.0.1:6379> PFADD hll_key_1 a b c d
(integer) 1
127.0.0.1:6379> PFADD hll_key_2 d e f
(integer) 1
127.0.0.1:6379> SET key_3 xyz
OK
127.0.0.1:6379> PFMERGE key_3 hll_key_1 hll_key_2
(error) WRONGTYPE Key is not a valid HyperLogLog string value.
127.0.0.1:6379>