cardinality-aggregation.asciidoc 7.4 KB

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