rare-terms-aggregation.asciidoc 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  1. [[search-aggregations-bucket-rare-terms-aggregation]]
  2. === Rare terms aggregation
  3. ++++
  4. <titleabbrev>Rare terms</titleabbrev>
  5. ++++
  6. A multi-bucket value source based aggregation which finds "rare" terms -- terms that are at the long-tail
  7. of the distribution and are not frequent. Conceptually, this is like a `terms` aggregation that is
  8. sorted by `_count` ascending. As noted in the <<search-aggregations-bucket-terms-aggregation-order,terms aggregation docs>>,
  9. actually ordering a `terms` agg by count ascending has unbounded error. Instead, you should use the `rare_terms`
  10. aggregation
  11. //////////////////////////
  12. [source,js]
  13. --------------------------------------------------
  14. PUT /products
  15. {
  16. "mappings": {
  17. "properties": {
  18. "genre": {
  19. "type": "keyword"
  20. },
  21. "product": {
  22. "type": "keyword"
  23. }
  24. }
  25. }
  26. }
  27. POST /products/_bulk?refresh
  28. {"index":{"_id":0}}
  29. {"genre": "rock", "product": "Product A"}
  30. {"index":{"_id":1}}
  31. {"genre": "rock"}
  32. {"index":{"_id":2}}
  33. {"genre": "rock"}
  34. {"index":{"_id":3}}
  35. {"genre": "jazz", "product": "Product Z"}
  36. {"index":{"_id":4}}
  37. {"genre": "jazz"}
  38. {"index":{"_id":5}}
  39. {"genre": "electronic"}
  40. {"index":{"_id":6}}
  41. {"genre": "electronic"}
  42. {"index":{"_id":7}}
  43. {"genre": "electronic"}
  44. {"index":{"_id":8}}
  45. {"genre": "electronic"}
  46. {"index":{"_id":9}}
  47. {"genre": "electronic"}
  48. {"index":{"_id":10}}
  49. {"genre": "swing"}
  50. -------------------------------------------------
  51. // NOTCONSOLE
  52. // TESTSETUP
  53. //////////////////////////
  54. ==== Syntax
  55. A `rare_terms` aggregation looks like this in isolation:
  56. [source,js]
  57. --------------------------------------------------
  58. {
  59. "rare_terms": {
  60. "field": "the_field",
  61. "max_doc_count": 1
  62. }
  63. }
  64. --------------------------------------------------
  65. // NOTCONSOLE
  66. .`rare_terms` Parameters
  67. |===
  68. |Parameter Name |Description |Required |Default Value
  69. |`field` |The field we wish to find rare terms in |Required |
  70. |`max_doc_count` |The maximum number of documents a term should appear in. |Optional |`1`
  71. |`precision` |The precision of the internal CuckooFilters. Smaller precision leads to
  72. better approximation, but higher memory usage. Cannot be smaller than `0.00001` |Optional |`0.01`
  73. |`include` |Terms that should be included in the aggregation|Optional |
  74. |`exclude` |Terms that should be excluded from the aggregation|Optional |
  75. |`missing` |The value that should be used if a document does not have the field being aggregated|Optional |
  76. |===
  77. Example:
  78. [source,console,id=rare-terms-aggregation-example]
  79. --------------------------------------------------
  80. GET /_search
  81. {
  82. "aggs": {
  83. "genres": {
  84. "rare_terms": {
  85. "field": "genre"
  86. }
  87. }
  88. }
  89. }
  90. --------------------------------------------------
  91. // TEST[s/_search/_search\?filter_path=aggregations/]
  92. Response:
  93. [source,console-result]
  94. --------------------------------------------------
  95. {
  96. ...
  97. "aggregations": {
  98. "genres": {
  99. "buckets": [
  100. {
  101. "key": "swing",
  102. "doc_count": 1
  103. }
  104. ]
  105. }
  106. }
  107. }
  108. --------------------------------------------------
  109. // TESTRESPONSE[s/\.\.\.//]
  110. In this example, the only bucket that we see is the "swing" bucket, because it is the only term that appears in
  111. one document. If we increase the `max_doc_count` to `2`, we'll see some more buckets:
  112. [source,console,id=rare-terms-aggregation-max-doc-count-example]
  113. --------------------------------------------------
  114. GET /_search
  115. {
  116. "aggs": {
  117. "genres": {
  118. "rare_terms": {
  119. "field": "genre",
  120. "max_doc_count": 2
  121. }
  122. }
  123. }
  124. }
  125. --------------------------------------------------
  126. // TEST[s/_search/_search\?filter_path=aggregations/]
  127. This now shows the "jazz" term which has a `doc_count` of 2":
  128. [source,console-result]
  129. --------------------------------------------------
  130. {
  131. ...
  132. "aggregations": {
  133. "genres": {
  134. "buckets": [
  135. {
  136. "key": "swing",
  137. "doc_count": 1
  138. },
  139. {
  140. "key": "jazz",
  141. "doc_count": 2
  142. }
  143. ]
  144. }
  145. }
  146. }
  147. --------------------------------------------------
  148. // TESTRESPONSE[s/\.\.\.//]
  149. [[search-aggregations-bucket-rare-terms-aggregation-max-doc-count]]
  150. ==== Maximum document count
  151. The `max_doc_count` parameter is used to control the upper bound of document counts that a term can have. There
  152. is not a size limitation on the `rare_terms` agg like `terms` agg has. This means that terms
  153. which match the `max_doc_count` criteria will be returned. The aggregation functions in this manner to avoid
  154. the order-by-ascending issues that afflict the `terms` aggregation.
  155. This does, however, mean that a large number of results can be returned if chosen incorrectly.
  156. To limit the danger of this setting, the maximum `max_doc_count` is 100.
  157. [[search-aggregations-bucket-rare-terms-aggregation-max-buckets]]
  158. ==== Max Bucket Limit
  159. The Rare Terms aggregation is more liable to trip the `search.max_buckets` soft limit than other aggregations due
  160. to how it works. The `max_bucket` soft-limit is evaluated on a per-shard basis while the aggregation is collecting
  161. results. It is possible for a term to be "rare" on a shard but become "not rare" once all the shard results are
  162. merged together. This means that individual shards tend to collect more buckets than are truly rare, because
  163. they only have their own local view. This list is ultimately pruned to the correct, smaller list of rare
  164. terms on the coordinating node... but a shard may have already tripped the `max_buckets` soft limit and aborted
  165. the request.
  166. When aggregating on fields that have potentially many "rare" terms, you may need to increase the `max_buckets` soft
  167. limit. Alternatively, you might need to find a way to filter the results to return fewer rare values (smaller time
  168. span, filter by category, etc), or re-evaluate your definition of "rare" (e.g. if something
  169. appears 100,000 times, is it truly "rare"?)
  170. [[search-aggregations-bucket-rare-terms-aggregation-approximate-counts]]
  171. ==== Document counts are approximate
  172. The naive way to determine the "rare" terms in a dataset is to place all the values in a map, incrementing counts
  173. as each document is visited, then return the bottom `n` rows. This does not scale beyond even modestly sized data
  174. sets. A sharded approach where only the "top n" values are retained from each shard (ala the `terms` aggregation)
  175. fails because the long-tail nature of the problem means it is impossible to find the "top n" bottom values without
  176. simply collecting all the values from all shards.
  177. Instead, the Rare Terms aggregation uses a different approximate algorithm:
  178. 1. Values are placed in a map the first time they are seen.
  179. 2. Each addition occurrence of the term increments a counter in the map
  180. 3. If the counter > the `max_doc_count` threshold, the term is removed from the map and placed in a
  181. https://www.cs.cmu.edu/~dga/papers/cuckoo-conext2014.pdf[CuckooFilter]
  182. 4. The CuckooFilter is consulted on each term. If the value is inside the filter, it is known to be above the
  183. threshold already and skipped.
  184. After execution, the map of values is the map of "rare" terms under the `max_doc_count` threshold. This map and CuckooFilter
  185. are then merged with all other shards. If there are terms that are greater than the threshold (or appear in
  186. a different shard's CuckooFilter) the term is removed from the merged list. The final map of values is returned
  187. to the user as the "rare" terms.
  188. CuckooFilters have the possibility of returning false positives (they can say a value exists in their collection when
  189. it actually does not). Since the CuckooFilter is being used to see if a term is over threshold, this means a false positive
  190. from the CuckooFilter will mistakenly say a value is common when it is not (and thus exclude it from it final list of buckets).
  191. Practically, this means the aggregations exhibits false-negative behavior since the filter is being used "in reverse"
  192. of how people generally think of approximate set membership sketches.
  193. CuckooFilters are described in more detail in the paper:
  194. https://www.cs.cmu.edu/~dga/papers/cuckoo-conext2014.pdf[Fan, Bin, et al. "Cuckoo filter: Practically better than bloom."]
  195. Proceedings of the 10th ACM International on Conference on emerging Networking Experiments and Technologies. ACM, 2014.
  196. ==== Precision
  197. Although the internal CuckooFilter is approximate in nature, the false-negative rate can be controlled with a
  198. `precision` parameter. This allows the user to trade more runtime memory for more accurate results.
  199. The default precision is `0.001`, and the smallest (e.g. most accurate and largest memory overhead) is `0.00001`.
  200. Below are some charts which demonstrate how the accuracy of the aggregation is affected by precision and number
  201. of distinct terms.
  202. The X-axis shows the number of distinct values the aggregation has seen, and the Y-axis shows the percent error.
  203. Each line series represents one "rarity" condition (ranging from one rare item to 100,000 rare items). For example,
  204. the orange "10" line means ten of the values were "rare" (`doc_count == 1`), out of 1-20m distinct values (where the
  205. rest of the values had `doc_count > 1`)
  206. This first chart shows precision `0.01`:
  207. image:images/rare_terms/accuracy_01.png[]
  208. And precision `0.001` (the default):
  209. image:images/rare_terms/accuracy_001.png[]
  210. And finally `precision 0.0001`:
  211. image:images/rare_terms/accuracy_0001.png[]
  212. The default precision of `0.001` maintains an accuracy of < 2.5% for the tested conditions, and accuracy slowly
  213. degrades in a controlled, linear fashion as the number of distinct values increases.
  214. The default precision of `0.001` has a memory profile of `1.748⁻⁶ * n` bytes, where `n` is the number
  215. of distinct values the aggregation has seen (it can also be roughly eyeballed, e.g. 20 million unique values is about
  216. 30mb of memory). The memory usage is linear to the number of distinct values regardless of which precision is chosen,
  217. the precision only affects the slope of the memory profile as seen in this chart:
  218. image:images/rare_terms/memory.png[]
  219. For comparison, an equivalent terms aggregation at 20 million buckets would be roughly
  220. `20m * 69b == ~1.38gb` (with 69 bytes being a very optimistic estimate of an empty bucket cost, far lower than what
  221. the circuit breaker accounts for). So although the `rare_terms` agg is relatively heavy, it is still orders of
  222. magnitude smaller than the equivalent terms aggregation
  223. ==== Filtering Values
  224. It is possible to filter the values for which buckets will be created. This can be done using the `include` and
  225. `exclude` parameters which are based on regular expression strings or arrays of exact values. Additionally,
  226. `include` clauses can filter using `partition` expressions.
  227. ===== Filtering Values with regular expressions
  228. [source,console,id=rare-terms-aggregation-regex-example]
  229. --------------------------------------------------
  230. GET /_search
  231. {
  232. "aggs": {
  233. "genres": {
  234. "rare_terms": {
  235. "field": "genre",
  236. "include": "swi*",
  237. "exclude": "electro*"
  238. }
  239. }
  240. }
  241. }
  242. --------------------------------------------------
  243. In the above example, buckets will be created for all the tags that starts with `swi`, except those starting
  244. with `electro` (so the tag `swing` will be aggregated but not `electro_swing`). The `include` regular expression will determine what
  245. values are "allowed" to be aggregated, while the `exclude` determines the values that should not be aggregated. When
  246. both are defined, the `exclude` has precedence, meaning, the `include` is evaluated first and only then the `exclude`.
  247. The syntax is the same as <<regexp-syntax,regexp queries>>.
  248. ===== Filtering Values with exact values
  249. For matching based on exact values the `include` and `exclude` parameters can simply take an array of
  250. strings that represent the terms as they are found in the index:
  251. [source,console,id=rare-terms-aggregation-exact-value-example]
  252. --------------------------------------------------
  253. GET /_search
  254. {
  255. "aggs": {
  256. "genres": {
  257. "rare_terms": {
  258. "field": "genre",
  259. "include": [ "swing", "rock" ],
  260. "exclude": [ "jazz" ]
  261. }
  262. }
  263. }
  264. }
  265. --------------------------------------------------
  266. ==== Missing value
  267. The `missing` parameter defines how documents that are missing a value should be treated.
  268. By default they will be ignored but it is also possible to treat them as if they
  269. had a value.
  270. [source,console,id=rare-terms-aggregation-missing-example]
  271. --------------------------------------------------
  272. GET /_search
  273. {
  274. "aggs": {
  275. "genres": {
  276. "rare_terms": {
  277. "field": "genre",
  278. "missing": "N/A" <1>
  279. }
  280. }
  281. }
  282. }
  283. --------------------------------------------------
  284. <1> Documents without a value in the `tags` field will fall into the same bucket as documents that have the value `N/A`.
  285. ==== Nested, RareTerms, and scoring sub-aggregations
  286. The RareTerms aggregation has to operate in `breadth_first` mode, since it needs to prune terms as doc count thresholds
  287. are breached. This requirement means the RareTerms aggregation is incompatible with certain combinations of aggregations
  288. that require `depth_first`. In particular, scoring sub-aggregations that are inside a `nested` force the entire aggregation tree to run
  289. in `depth_first` mode. This will throw an exception since RareTerms is unable to process `depth_first`.
  290. As a concrete example, if `rare_terms` aggregation is the child of a `nested` aggregation, and one of the child aggregations of `rare_terms`
  291. needs document scores (like a `top_hits` aggregation), this will throw an exception.