cardinality-aggregation.asciidoc 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  1. [[search-aggregations-metrics-cardinality-aggregation]]
  2. === Cardinality Aggregation
  3. A `single-value` metrics aggregation that calculates an approximate count of
  4. distinct values. Values can be extracted either from specific fields in the
  5. document or generated by a script.
  6. Assume you are indexing books and would like to count the unique authors that
  7. match a query:
  8. [source,js]
  9. --------------------------------------------------
  10. {
  11. "aggs" : {
  12. "author_count" : {
  13. "cardinality" : {
  14. "field" : "author"
  15. }
  16. }
  17. }
  18. }
  19. --------------------------------------------------
  20. ==== Precision control
  21. This aggregation also supports the `precision_threshold` option:
  22. experimental[The `precision_threshold` option is specific to the current internal implementation of the `cardinality` agg, which may change in the future]
  23. [source,js]
  24. --------------------------------------------------
  25. {
  26. "aggs" : {
  27. "author_count" : {
  28. "cardinality" : {
  29. "field" : "author_hash",
  30. "precision_threshold": 100 <1>
  31. }
  32. }
  33. }
  34. }
  35. --------------------------------------------------
  36. <1> The `precision_threshold` options allows to trade memory for accuracy, and
  37. defines a unique count below which counts are expected to be close to
  38. accurate. Above this value, counts might become a bit more fuzzy. The maximum
  39. supported value is 40000, thresholds above this number will have the same
  40. effect as a threshold of 40000. The default values is +3000+.
  41. ==== Counts are approximate
  42. Computing exact counts requires loading values into a hash set and returning its
  43. size. This doesn't scale when working on high-cardinality sets and/or large
  44. values as the required memory usage and the need to communicate those
  45. per-shard sets between nodes would utilize too many resources of the cluster.
  46. This `cardinality` aggregation is based on the
  47. http://static.googleusercontent.com/media/research.google.com/fr//pubs/archive/40671.pdf[HyperLogLog++]
  48. algorithm, which counts based on the hashes of the values with some interesting
  49. properties:
  50. * configurable precision, which decides on how to trade memory for accuracy,
  51. * excellent accuracy on low-cardinality sets,
  52. * fixed memory usage: no matter if there are tens or billions of unique values,
  53. memory usage only depends on the configured precision.
  54. For a precision threshold of `c`, the implementation that we are using requires
  55. about `c * 8` bytes.
  56. The following chart shows how the error varies before and after the threshold:
  57. ////
  58. To generate this chart use this gnuplot script:
  59. [source,gnuplot]
  60. -------
  61. #!/usr/bin/gnuplot
  62. reset
  63. set terminal png size 1000,400
  64. set xlabel "Actual cardinality"
  65. set logscale x
  66. set ylabel "Relative error (%)"
  67. set yrange [0:8]
  68. set title "Cardinality error"
  69. set grid
  70. set style data lines
  71. plot "test.dat" using 1:2 title "threshold=100", \
  72. "" using 1:3 title "threshold=1000", \
  73. "" using 1:4 title "threshold=10000"
  74. #
  75. -------
  76. and generate data in a 'test.dat' file using the below Java code:
  77. [source,java]
  78. -------
  79. private static double error(HyperLogLogPlusPlus h, long expected) {
  80. double actual = h.cardinality(0);
  81. return Math.abs(expected - actual) / expected;
  82. }
  83. public static void main(String[] args) {
  84. HyperLogLogPlusPlus h100 = new HyperLogLogPlusPlus(precisionFromThreshold(100), BigArrays.NON_RECYCLING_INSTANCE, 1);
  85. HyperLogLogPlusPlus h1000 = new HyperLogLogPlusPlus(precisionFromThreshold(1000), BigArrays.NON_RECYCLING_INSTANCE, 1);
  86. HyperLogLogPlusPlus h10000 = new HyperLogLogPlusPlus(precisionFromThreshold(10000), BigArrays.NON_RECYCLING_INSTANCE, 1);
  87. int next = 100;
  88. int step = 10;
  89. for (int i = 1; i <= 10000000; ++i) {
  90. long h = BitMixer.mix64(i);
  91. h100.collect(0, h);
  92. h1000.collect(0, h);
  93. h10000.collect(0, h);
  94. if (i == next) {
  95. System.out.println(i + " " + error(h100, i)*100 + " " + error(h1000, i)*100 + " " + error(h10000, i)*100);
  96. next += step;
  97. if (next >= 100 * step) {
  98. step *= 10;
  99. }
  100. }
  101. }
  102. }
  103. -------
  104. ////
  105. image:images/cardinality_error.png[]
  106. For all 3 thresholds, counts have been accurate up to the configured threshold
  107. (although not guaranteed, this is likely to be the case). Please also note that
  108. even with a threshold as low as 100, the error remains very low, even when
  109. counting millions of items.
  110. ==== Pre-computed hashes
  111. On string fields that have a high cardinality, it might be faster to store the
  112. hash of your field values in your index and then run the cardinality aggregation
  113. on this field. This can either be done by providing hash values from client-side
  114. or by letting elasticsearch compute hash values for you by using the
  115. {plugins}/mapper-murmur3.html[`mapper-murmur3`] plugin.
  116. NOTE: Pre-computing hashes is usually only useful on very large and/or
  117. high-cardinality fields as it saves CPU and memory. However, on numeric
  118. fields, hashing is very fast and storing the original values requires as much
  119. or less memory than storing the hashes. This is also true on low-cardinality
  120. string fields, especially given that those have an optimization in order to
  121. make sure that hashes are computed at most once per unique value per segment.
  122. ==== Script
  123. The `cardinality` metric supports scripting, with a noticeable performance hit
  124. however since hashes need to be computed on the fly.
  125. [source,js]
  126. --------------------------------------------------
  127. {
  128. "aggs" : {
  129. "author_count" : {
  130. "cardinality" : {
  131. "script": {
  132. "lang": "painless",
  133. "inline": "doc['author.first_name'].value + ' ' + doc['author.last_name'].value"
  134. }
  135. }
  136. }
  137. }
  138. }
  139. --------------------------------------------------
  140. This will interpret the `script` parameter as an `inline` script with the `painless` script language and no script parameters. To use a file script use the following syntax:
  141. [source,js]
  142. --------------------------------------------------
  143. {
  144. "aggs" : {
  145. "author_count" : {
  146. "cardinality" : {
  147. "script" : {
  148. "file": "my_script",
  149. "params": {
  150. "first_name_field": "author.first_name",
  151. "last_name_field": "author.last_name"
  152. }
  153. }
  154. }
  155. }
  156. }
  157. }
  158. --------------------------------------------------
  159. TIP: for indexed scripts replace the `file` parameter with an `id` parameter.
  160. ==== Missing value
  161. The `missing` parameter defines how documents that are missing a value should be treated.
  162. By default they will be ignored but it is also possible to treat them as if they
  163. had a value.
  164. [source,js]
  165. --------------------------------------------------
  166. {
  167. "aggs" : {
  168. "tag_cardinality" : {
  169. "cardinality" : {
  170. "field" : "tag",
  171. "missing": "N/A" <1>
  172. }
  173. }
  174. }
  175. }
  176. --------------------------------------------------
  177. <1> Documents without a value in the `tag` field will fall into the same bucket as documents that have the value `N/A`.