cardinality-aggregation.asciidoc 7.5 KB

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