# Unique Counting

Unique counting is a classic problem. Pinot solves it with multiple ways to trade-off between accuracy and latency.

## Accurate Results

Functions:

* ***DistinctCount**(x) -> LONG*

Returns accurate count for all unique values in a column.

The underlying implementation is using a IntOpenHashSet in library: `it.unimi.dsi:fastutil:8.2.3` to hold all the unique values.

## Approximation Results

Usually it takes a lot of resources and time to compute accurate results for unique counting. In some circumstance, users could tolerate with certain error rate, then we could use approximation functions to tackle this problem.

### HyperLogLog

[HyperLogLog](https://en.wikipedia.org/wiki/HyperLogLog) is one approximation algorithm for unique counting. It uses fixed number of bits to estimate the cardinality of given data set.

Pinot leverages [HyperLogLog Class](https://github.com/addthis/stream-lib/blob/master/src/main/java/com/clearspring/analytics/stream/cardinality/HyperLogLog.java) in library `com.clearspring.analytics:stream:2.7.0`as the data structure to hold intermediate results.

Functions:

* ***DistinctCountHLL**(x) -> LONG*

For column type **INT**/**LONG**/**FLOAT**/**DOUBLE**/**STRING** , Pinot treats each value as an individual entry to add into HyperLogLog Object, then compute the approximation by calling method ***cardinality()***.

For column type **BYTES**, Pinot treats each value as a serialized HyperLogLog Object with pre-aggregated values inside. The bytes value is generated by `org.apache.pinot.core.common.ObjectSerDeUtils.HYPER_LOG_LOG_SER_DE.serialize(hyperLogLog)`.

All deserialized HyperLogLog object will be merged into one then calling method ***cardinality()** to get the approximated unique count.*
