count-distinct.asciidoc 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. [[esql-agg-count-distinct]]
  2. === `COUNT_DISTINCT`
  3. The approximate number of distinct values.
  4. [source.merge.styled,esql]
  5. ----
  6. include::{esql-specs}/stats_count_distinct.csv-spec[tag=count-distinct]
  7. ----
  8. [%header.monospaced.styled,format=dsv,separator=|]
  9. |===
  10. include::{esql-specs}/stats_count_distinct.csv-spec[tag=count-distinct-result]
  11. |===
  12. Can take any field type as input and the result is always a `long` not matter
  13. the input type.
  14. ==== Counts are approximate
  15. Computing exact counts requires loading values into a set and returning its
  16. size. This doesn't scale when working on high-cardinality sets and/or large
  17. values as the required memory usage and the need to communicate those
  18. per-shard sets between nodes would utilize too many resources of the cluster.
  19. This `COUNT_DISTINCT` function is based on the
  20. https://static.googleusercontent.com/media/research.google.com/fr//pubs/archive/40671.pdf[HyperLogLog++]
  21. algorithm, which counts based on the hashes of the values with some interesting
  22. properties:
  23. include::../../aggregations/metrics/cardinality-aggregation.asciidoc[tag=explanation]
  24. ==== Precision is configurable
  25. The `COUNT_DISTINCT` function takes an optional second parameter to configure the
  26. precision discussed previously.
  27. [source.merge.styled,esql]
  28. ----
  29. include::{esql-specs}/stats_count_distinct.csv-spec[tag=count-distinct-precision]
  30. ----
  31. [%header.monospaced.styled,format=dsv,separator=|]
  32. |===
  33. include::{esql-specs}/stats_count_distinct.csv-spec[tag=count-distinct-precision-result]
  34. |===