Redis HyperLogLog PFADD Command
The PFADD
command in Redis adds one or more elements to a HyperLogLog data structure.
Syntax
The basic syntax for the PFADD
command is as follows:
1 | PFADD key [element [element ...]] |
This command adds all the specified elements to the HyperLogLog data structure stored at the key provided as the first argument.
Available Since
Redis version 2.8.9 and later.
Time Complexity
O(1) to add every element.
ACL Categories
@write
, @hyperloglog
, @fast
Return Value
Returns an integer:
1
if at least one element was added.0
if no new elements were added.
As a result, the internal state of the HyperLogLog may be updated, reflecting a new estimation of the cardinality (the number of unique items) based on the added elements.
If the estimated cardinality changes after executing the command,
PFADD
returns 1. If no change occurs, it returns 0. If the key doesn’t already exist, the command creates an empty HyperLogLog data structure (a Redis string with a specified length and encoding).
Example 1
1 | 127.0.0.1:6379> PFADD hll_key redis mysql hbase |
Example 2
You can also call the command with only a key and no elements. In this case:
- If the key already exists, no operation is performed.
- If the key doesn’t exist, a new HyperLogLog structure is created, and the command returns 1.
For example, if Redis already has a HyperLogLog for the key hll_key
and you call the command with just the key and no elements (e.g., PFADD hll_key
), it will return 0. If the key doesn’t exist (e.g., PFADD hll_key_2
), the command will create an empty HyperLogLog data structure and return 1.
1 | 127.0.0.1:6379> PFCOUNT hll_key |