terms-aggregation.asciidoc 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780
  1. [[search-aggregations-bucket-terms-aggregation]]
  2. === Terms aggregation
  3. ++++
  4. <titleabbrev>Terms</titleabbrev>
  5. ++++
  6. A multi-bucket value source based aggregation where buckets are dynamically built - one per unique value.
  7. //////////////////////////
  8. [source,js]
  9. --------------------------------------------------
  10. PUT /products
  11. {
  12. "mappings": {
  13. "properties": {
  14. "genre": {
  15. "type": "keyword"
  16. },
  17. "product": {
  18. "type": "keyword"
  19. }
  20. }
  21. }
  22. }
  23. POST /products/_bulk?refresh
  24. {"index":{"_id":0}}
  25. {"genre": "rock", "product": "Product A"}
  26. {"index":{"_id":1}}
  27. {"genre": "rock"}
  28. {"index":{"_id":2}}
  29. {"genre": "rock"}
  30. {"index":{"_id":3}}
  31. {"genre": "jazz", "product": "Product Z"}
  32. {"index":{"_id":4}}
  33. {"genre": "jazz"}
  34. {"index":{"_id":5}}
  35. {"genre": "electronic"}
  36. {"index":{"_id":6}}
  37. {"genre": "electronic"}
  38. {"index":{"_id":7}}
  39. {"genre": "electronic"}
  40. {"index":{"_id":8}}
  41. {"genre": "electronic"}
  42. {"index":{"_id":9}}
  43. {"genre": "electronic"}
  44. {"index":{"_id":10}}
  45. {"genre": "electronic"}
  46. -------------------------------------------------
  47. // NOTCONSOLE
  48. // TESTSETUP
  49. //////////////////////////
  50. Example:
  51. [source,console,id=terms-aggregation-example]
  52. --------------------------------------------------
  53. GET /_search
  54. {
  55. "aggs": {
  56. "genres": {
  57. "terms": { "field": "genre" } <1>
  58. }
  59. }
  60. }
  61. --------------------------------------------------
  62. // TEST[s/_search/_search\?filter_path=aggregations/]
  63. <1> `terms` aggregation should be a field of type `keyword` or any other data type suitable for bucket aggregations. In order to use it with `text` you will need to enable
  64. <<fielddata, fielddata>>.
  65. Response:
  66. [source,console-result]
  67. --------------------------------------------------
  68. {
  69. ...
  70. "aggregations": {
  71. "genres": {
  72. "doc_count_error_upper_bound": 0, <1>
  73. "sum_other_doc_count": 0, <2>
  74. "buckets": [ <3>
  75. {
  76. "key": "electronic",
  77. "doc_count": 6
  78. },
  79. {
  80. "key": "rock",
  81. "doc_count": 3
  82. },
  83. {
  84. "key": "jazz",
  85. "doc_count": 2
  86. }
  87. ]
  88. }
  89. }
  90. }
  91. --------------------------------------------------
  92. // TESTRESPONSE[s/\.\.\.//]
  93. <1> an upper bound of the error on the document counts for each term, see <<search-aggregations-bucket-terms-aggregation-approximate-counts,below>>
  94. <2> when there are lots of unique terms, Elasticsearch only returns the top terms; this number is the sum of the document counts for all buckets that are not part of the response
  95. <3> the list of the top buckets, the meaning of `top` being defined by the <<search-aggregations-bucket-terms-aggregation-order,order>>
  96. By default, the `terms` aggregation will return the buckets for the top ten terms ordered by the `doc_count`. One can
  97. change this default behaviour by setting the `size` parameter.
  98. [[search-aggregations-bucket-terms-aggregation-size]]
  99. ==== Size
  100. The `size` parameter can be set to define how many term buckets should be returned out of the overall terms list. By
  101. default, the node coordinating the search process will request each shard to provide its own top `size` term buckets
  102. and once all shards respond, it will reduce the results to the final list that will then be returned to the client.
  103. This means that if the number of unique terms is greater than `size`, the returned list is slightly off and not accurate
  104. (it could be that the term counts are slightly off and it could even be that a term that should have been in the top
  105. size buckets was not returned).
  106. NOTE: If you want to retrieve **all** terms or all combinations of terms in a nested `terms` aggregation
  107. you should use the <<search-aggregations-bucket-composite-aggregation,Composite>> aggregation which
  108. allows to paginate over all possible terms rather than setting a size greater than the cardinality of the field in the
  109. `terms` aggregation. The `terms` aggregation is meant to return the `top` terms and does not allow pagination.
  110. [[search-aggregations-bucket-terms-aggregation-approximate-counts]]
  111. ==== Document counts are approximate
  112. Document counts (and the results of any sub aggregations) in the terms
  113. aggregation are not always accurate. Each shard provides its own view of what
  114. the ordered list of terms should be. These views are combined to give a final
  115. view.
  116. ==== Shard Size
  117. The higher the requested `size` is, the more accurate the results will be, but also, the more expensive it will be to
  118. compute the final results (both due to bigger priority queues that are managed on a shard level and due to bigger data
  119. transfers between the nodes and the client).
  120. The `shard_size` parameter can be used to minimize the extra work that comes with bigger requested `size`. When defined,
  121. it will determine how many terms the coordinating node will request from each shard. Once all the shards responded, the
  122. coordinating node will then reduce them to a final result which will be based on the `size` parameter - this way,
  123. one can increase the accuracy of the returned terms and avoid the overhead of streaming a big list of buckets back to
  124. the client.
  125. NOTE: `shard_size` cannot be smaller than `size` (as it doesn't make much sense). When it is, Elasticsearch will
  126. override it and reset it to be equal to `size`.
  127. The default `shard_size` is `(size * 1.5 + 10)`.
  128. ==== Calculating Document Count Error
  129. There are two error values which can be shown on the terms aggregation. The first gives a value for the aggregation as
  130. a whole which represents the maximum potential document count for a term which did not make it into the final list of
  131. terms. This is calculated as the sum of the document count from the last term returned from each shard.
  132. ==== Per bucket document count error
  133. The second error value can be enabled by setting the `show_term_doc_count_error` parameter to true:
  134. [source,console,id=terms-aggregation-doc-count-error-example]
  135. --------------------------------------------------
  136. GET /_search
  137. {
  138. "aggs": {
  139. "products": {
  140. "terms": {
  141. "field": "product",
  142. "size": 5,
  143. "show_term_doc_count_error": true
  144. }
  145. }
  146. }
  147. }
  148. --------------------------------------------------
  149. // TEST[s/_search/_search\?filter_path=aggregations/]
  150. This shows an error value for each term returned by the aggregation which represents the 'worst case' error in the document count
  151. and can be useful when deciding on a value for the `shard_size` parameter. This is calculated by summing the document counts for
  152. the last term returned by all shards which did not return the term.
  153. These errors can only be calculated in this way when the terms are ordered by descending document count. When the aggregation is
  154. ordered by the terms values themselves (either ascending or descending) there is no error in the document count since if a shard
  155. does not return a particular term which appears in the results from another shard, it must not have that term in its index. When the
  156. aggregation is either sorted by a sub aggregation or in order of ascending document count, the error in the document counts cannot be
  157. determined and is given a value of -1 to indicate this.
  158. [[search-aggregations-bucket-terms-aggregation-order]]
  159. ==== Order
  160. The order of the buckets can be customized by setting the `order` parameter. By default, the buckets are ordered by
  161. their `doc_count` descending. It is possible to change this behaviour as documented below:
  162. WARNING: Sorting by ascending `_count` or by sub aggregation is discouraged as it increases the
  163. <<search-aggregations-bucket-terms-aggregation-approximate-counts,error>> on document counts.
  164. It is fine when a single shard is queried, or when the field that is being aggregated was used
  165. as a routing key at index time: in these cases results will be accurate since shards have disjoint
  166. values. However otherwise, errors are unbounded. One particular case that could still be useful
  167. is sorting by <<search-aggregations-metrics-min-aggregation,`min`>> or
  168. <<search-aggregations-metrics-max-aggregation,`max`>> aggregation: counts will not be accurate
  169. but at least the top buckets will be correctly picked.
  170. Ordering the buckets by their doc `_count` in an ascending manner:
  171. [source,console,id=terms-aggregation-count-example]
  172. --------------------------------------------------
  173. GET /_search
  174. {
  175. "aggs": {
  176. "genres": {
  177. "terms": {
  178. "field": "genre",
  179. "order": { "_count": "asc" }
  180. }
  181. }
  182. }
  183. }
  184. --------------------------------------------------
  185. Ordering the buckets alphabetically by their terms in an ascending manner:
  186. [source,console,id=terms-aggregation-asc-example]
  187. --------------------------------------------------
  188. GET /_search
  189. {
  190. "aggs": {
  191. "genres": {
  192. "terms": {
  193. "field": "genre",
  194. "order": { "_key": "asc" }
  195. }
  196. }
  197. }
  198. }
  199. --------------------------------------------------
  200. deprecated[6.0.0, Use `_key` instead of `_term` to order buckets by their term]
  201. Ordering the buckets by single value metrics sub-aggregation (identified by the aggregation name):
  202. [source,console,id=terms-aggregation-subaggregation-example]
  203. --------------------------------------------------
  204. GET /_search
  205. {
  206. "aggs": {
  207. "genres": {
  208. "terms": {
  209. "field": "genre",
  210. "order": { "max_play_count": "desc" }
  211. },
  212. "aggs": {
  213. "max_play_count": { "max": { "field": "play_count" } }
  214. }
  215. }
  216. }
  217. }
  218. --------------------------------------------------
  219. Ordering the buckets by multi value metrics sub-aggregation (identified by the aggregation name):
  220. [source,console,id=terms-aggregation-multivalue-subaggregation-example]
  221. --------------------------------------------------
  222. GET /_search
  223. {
  224. "aggs": {
  225. "genres": {
  226. "terms": {
  227. "field": "genre",
  228. "order": { "playback_stats.max": "desc" }
  229. },
  230. "aggs": {
  231. "playback_stats": { "stats": { "field": "play_count" } }
  232. }
  233. }
  234. }
  235. }
  236. --------------------------------------------------
  237. [NOTE]
  238. .Pipeline aggs cannot be used for sorting
  239. =======================================
  240. <<search-aggregations-pipeline,Pipeline aggregations>> are run during the
  241. reduce phase after all other aggregations have already completed. For this
  242. reason, they cannot be used for ordering.
  243. =======================================
  244. It is also possible to order the buckets based on a "deeper" aggregation in the hierarchy. This is supported as long
  245. as the aggregations path are of a single-bucket type, where the last aggregation in the path may either be a single-bucket
  246. one or a metrics one. If it's a single-bucket type, the order will be defined by the number of docs in the bucket (i.e. `doc_count`),
  247. in case it's a metrics one, the same rules as above apply (where the path must indicate the metric name to sort by in case of
  248. a multi-value metrics aggregation, and in case of a single-value metrics aggregation the sort will be applied on that value).
  249. The path must be defined in the following form:
  250. // {wikipedia}/Extended_Backus%E2%80%93Naur_Form
  251. [source,ebnf]
  252. --------------------------------------------------
  253. AGG_SEPARATOR = '>' ;
  254. METRIC_SEPARATOR = '.' ;
  255. AGG_NAME = <the name of the aggregation> ;
  256. METRIC = <the name of the metric (in case of multi-value metrics aggregation)> ;
  257. PATH = <AGG_NAME> [ <AGG_SEPARATOR>, <AGG_NAME> ]* [ <METRIC_SEPARATOR>, <METRIC> ] ;
  258. --------------------------------------------------
  259. [source,console,id=terms-aggregation-hierarchy-example]
  260. --------------------------------------------------
  261. GET /_search
  262. {
  263. "aggs": {
  264. "countries": {
  265. "terms": {
  266. "field": "artist.country",
  267. "order": { "rock>playback_stats.avg": "desc" }
  268. },
  269. "aggs": {
  270. "rock": {
  271. "filter": { "term": { "genre": "rock" } },
  272. "aggs": {
  273. "playback_stats": { "stats": { "field": "play_count" } }
  274. }
  275. }
  276. }
  277. }
  278. }
  279. }
  280. --------------------------------------------------
  281. The above will sort the artist's countries buckets based on the average play count among the rock songs.
  282. Multiple criteria can be used to order the buckets by providing an array of order criteria such as the following:
  283. [source,console,id=terms-aggregation-multicriteria-example]
  284. --------------------------------------------------
  285. GET /_search
  286. {
  287. "aggs": {
  288. "countries": {
  289. "terms": {
  290. "field": "artist.country",
  291. "order": [ { "rock>playback_stats.avg": "desc" }, { "_count": "desc" } ]
  292. },
  293. "aggs": {
  294. "rock": {
  295. "filter": { "term": { "genre": "rock" } },
  296. "aggs": {
  297. "playback_stats": { "stats": { "field": "play_count" } }
  298. }
  299. }
  300. }
  301. }
  302. }
  303. }
  304. --------------------------------------------------
  305. The above will sort the artist's countries buckets based on the average play count among the rock songs and then by
  306. their `doc_count` in descending order.
  307. NOTE: In the event that two buckets share the same values for all order criteria the bucket's term value is used as a
  308. tie-breaker in ascending alphabetical order to prevent non-deterministic ordering of buckets.
  309. ==== Minimum document count
  310. It is possible to only return terms that match more than a configured number of hits using the `min_doc_count` option:
  311. [source,console,id=terms-aggregation-min-doc-count-example]
  312. --------------------------------------------------
  313. GET /_search
  314. {
  315. "aggs": {
  316. "tags": {
  317. "terms": {
  318. "field": "tags",
  319. "min_doc_count": 10
  320. }
  321. }
  322. }
  323. }
  324. --------------------------------------------------
  325. The above aggregation would only return tags which have been found in 10 hits or more. Default value is `1`.
  326. Terms are collected and ordered on a shard level and merged with the terms collected from other shards in a second step. However, the shard does not have the information about the global document count available. The decision if a term is added to a candidate list depends only on the order computed on the shard using local shard frequencies. The `min_doc_count` criterion is only applied after merging local terms statistics of all shards. In a way the decision to add the term as a candidate is made without being very _certain_ about if the term will actually reach the required `min_doc_count`. This might cause many (globally) high frequent terms to be missing in the final result if low frequent terms populated the candidate lists. To avoid this, the `shard_size` parameter can be increased to allow more candidate terms on the shards. However, this increases memory consumption and network traffic.
  327. `shard_min_doc_count` parameter
  328. The parameter `shard_min_doc_count` regulates the _certainty_ a shard has if the term should actually be added to the candidate list or not with respect to the `min_doc_count`. Terms will only be considered if their local shard frequency within the set is higher than the `shard_min_doc_count`. If your dictionary contains many low frequent terms and you are not interested in those (for example misspellings), then you can set the `shard_min_doc_count` parameter to filter out candidate terms on a shard level that will with a reasonable certainty not reach the required `min_doc_count` even after merging the local counts. `shard_min_doc_count` is set to `0` per default and has no effect unless you explicitly set it.
  329. NOTE: Setting `min_doc_count`=`0` will also return buckets for terms that didn't match any hit. However, some of
  330. the returned terms which have a document count of zero might only belong to deleted documents or documents
  331. from other types, so there is no warranty that a `match_all` query would find a positive document count for
  332. those terms.
  333. WARNING: When NOT sorting on `doc_count` descending, high values of `min_doc_count` may return a number of buckets
  334. which is less than `size` because not enough data was gathered from the shards. Missing buckets can be
  335. back by increasing `shard_size`.
  336. Setting `shard_min_doc_count` too high will cause terms to be filtered out on a shard level. This value should be set much lower than `min_doc_count/#shards`.
  337. [[search-aggregations-bucket-terms-aggregation-script]]
  338. ==== Script
  339. Generating the terms using a script:
  340. [source,console,id=terms-aggregation-script-example]
  341. --------------------------------------------------
  342. GET /_search
  343. {
  344. "aggs": {
  345. "genres": {
  346. "terms": {
  347. "script": {
  348. "source": "doc['genre'].value",
  349. "lang": "painless"
  350. }
  351. }
  352. }
  353. }
  354. }
  355. --------------------------------------------------
  356. This will interpret the `script` parameter as an `inline` script with the default script language and no script parameters. To use a stored script use the following syntax:
  357. //////////////////////////
  358. [source,console,id=terms-aggregation-stored-example]
  359. --------------------------------------------------
  360. POST /_scripts/my_script
  361. {
  362. "script": {
  363. "lang": "painless",
  364. "source": "doc[params.field].value"
  365. }
  366. }
  367. --------------------------------------------------
  368. //////////////////////////
  369. [source,console]
  370. --------------------------------------------------
  371. GET /_search
  372. {
  373. "aggs": {
  374. "genres": {
  375. "terms": {
  376. "script": {
  377. "id": "my_script",
  378. "params": {
  379. "field": "genre"
  380. }
  381. }
  382. }
  383. }
  384. }
  385. }
  386. --------------------------------------------------
  387. // TEST[continued]
  388. ==== Value Script
  389. [source,console,id=terms-aggregation-value-script-example]
  390. --------------------------------------------------
  391. GET /_search
  392. {
  393. "aggs": {
  394. "genres": {
  395. "terms": {
  396. "field": "genre",
  397. "script": {
  398. "source": "'Genre: ' +_value",
  399. "lang": "painless"
  400. }
  401. }
  402. }
  403. }
  404. }
  405. --------------------------------------------------
  406. ==== Filtering Values
  407. It is possible to filter the values for which buckets will be created. This can be done using the `include` and
  408. `exclude` parameters which are based on regular expression strings or arrays of exact values. Additionally,
  409. `include` clauses can filter using `partition` expressions.
  410. ===== Filtering Values with regular expressions
  411. [source,console,id=terms-aggregation-regex-example]
  412. --------------------------------------------------
  413. GET /_search
  414. {
  415. "aggs": {
  416. "tags": {
  417. "terms": {
  418. "field": "tags",
  419. "include": ".*sport.*",
  420. "exclude": "water_.*"
  421. }
  422. }
  423. }
  424. }
  425. --------------------------------------------------
  426. In the above example, buckets will be created for all the tags that has the word `sport` in them, except those starting
  427. with `water_` (so the tag `water_sports` will not be aggregated). The `include` regular expression will determine what
  428. values are "allowed" to be aggregated, while the `exclude` determines the values that should not be aggregated. When
  429. both are defined, the `exclude` has precedence, meaning, the `include` is evaluated first and only then the `exclude`.
  430. The syntax is the same as <<regexp-syntax,regexp queries>>.
  431. ===== Filtering Values with exact values
  432. For matching based on exact values the `include` and `exclude` parameters can simply take an array of
  433. strings that represent the terms as they are found in the index:
  434. [source,console,id=terms-aggregation-exact-example]
  435. --------------------------------------------------
  436. GET /_search
  437. {
  438. "aggs": {
  439. "JapaneseCars": {
  440. "terms": {
  441. "field": "make",
  442. "include": [ "mazda", "honda" ]
  443. }
  444. },
  445. "ActiveCarManufacturers": {
  446. "terms": {
  447. "field": "make",
  448. "exclude": [ "rover", "jensen" ]
  449. }
  450. }
  451. }
  452. }
  453. --------------------------------------------------
  454. ===== Filtering Values with partitions
  455. Sometimes there are too many unique terms to process in a single request/response pair so
  456. it can be useful to break the analysis up into multiple requests.
  457. This can be achieved by grouping the field's values into a number of partitions at query-time and processing
  458. only one partition in each request.
  459. Consider this request which is looking for accounts that have not logged any access recently:
  460. [source,console,id=terms-aggregation-partitions-example]
  461. --------------------------------------------------
  462. GET /_search
  463. {
  464. "size": 0,
  465. "aggs": {
  466. "expired_sessions": {
  467. "terms": {
  468. "field": "account_id",
  469. "include": {
  470. "partition": 0,
  471. "num_partitions": 20
  472. },
  473. "size": 10000,
  474. "order": {
  475. "last_access": "asc"
  476. }
  477. },
  478. "aggs": {
  479. "last_access": {
  480. "max": {
  481. "field": "access_date"
  482. }
  483. }
  484. }
  485. }
  486. }
  487. }
  488. --------------------------------------------------
  489. This request is finding the last logged access date for a subset of customer accounts because we
  490. might want to expire some customer accounts who haven't been seen for a long while.
  491. The `num_partitions` setting has requested that the unique account_ids are organized evenly into twenty
  492. partitions (0 to 19). and the `partition` setting in this request filters to only consider account_ids falling
  493. into partition 0. Subsequent requests should ask for partitions 1 then 2 etc to complete the expired-account analysis.
  494. Note that the `size` setting for the number of results returned needs to be tuned with the `num_partitions`.
  495. For this particular account-expiration example the process for balancing values for `size` and `num_partitions` would be as follows:
  496. 1. Use the `cardinality` aggregation to estimate the total number of unique account_id values
  497. 2. Pick a value for `num_partitions` to break the number from 1) up into more manageable chunks
  498. 3. Pick a `size` value for the number of responses we want from each partition
  499. 4. Run a test request
  500. If we have a circuit-breaker error we are trying to do too much in one request and must increase `num_partitions`.
  501. If the request was successful but the last account ID in the date-sorted test response was still an account we might want to
  502. expire then we may be missing accounts of interest and have set our numbers too low. We must either
  503. * increase the `size` parameter to return more results per partition (could be heavy on memory) or
  504. * increase the `num_partitions` to consider less accounts per request (could increase overall processing time as we need to make more requests)
  505. Ultimately this is a balancing act between managing the Elasticsearch resources required to process a single request and the volume
  506. of requests that the client application must issue to complete a task.
  507. WARNING: Partitions cannot be used together with an `exclude` parameter.
  508. ==== Multi-field terms aggregation
  509. The `terms` aggregation does not support collecting terms from multiple fields
  510. in the same document. The reason is that the `terms` agg doesn't collect the
  511. string term values themselves, but rather uses
  512. <<search-aggregations-bucket-terms-aggregation-execution-hint,global ordinals>>
  513. to produce a list of all of the unique values in the field. Global ordinals
  514. results in an important performance boost which would not be possible across
  515. multiple fields.
  516. There are three approaches that you can use to perform a `terms` agg across
  517. multiple fields:
  518. <<search-aggregations-bucket-terms-aggregation-script,Script>>::
  519. Use a script to retrieve terms from multiple fields. This disables the global
  520. ordinals optimization and will be slower than collecting terms from a single
  521. field, but it gives you the flexibility to implement this option at search
  522. time.
  523. <<copy-to,`copy_to` field>>::
  524. If you know ahead of time that you want to collect the terms from two or more
  525. fields, then use `copy_to` in your mapping to create a new dedicated field at
  526. index time which contains the values from both fields. You can aggregate on
  527. this single field, which will benefit from the global ordinals optimization.
  528. <<search-aggregations-bucket-multi-terms-aggregation, `multi_terms` aggregation>>::
  529. Use multi_terms aggregation to combine terms from multiple fields into a compound key. This
  530. also disables the global ordinals and will be slower than collecting terms from a single field.
  531. It is faster but less flexible than using a script.
  532. [[search-aggregations-bucket-terms-aggregation-collect]]
  533. ==== Collect mode
  534. Deferring calculation of child aggregations
  535. For fields with many unique terms and a small number of required results it can be more efficient to delay the calculation
  536. of child aggregations until the top parent-level aggs have been pruned. Ordinarily, all branches of the aggregation tree
  537. are expanded in one depth-first pass and only then any pruning occurs.
  538. In some scenarios this can be very wasteful and can hit memory constraints.
  539. An example problem scenario is querying a movie database for the 10 most popular actors and their 5 most common co-stars:
  540. [source,console,id=terms-aggregation-collect-mode-example]
  541. --------------------------------------------------
  542. GET /_search
  543. {
  544. "aggs": {
  545. "actors": {
  546. "terms": {
  547. "field": "actors",
  548. "size": 10
  549. },
  550. "aggs": {
  551. "costars": {
  552. "terms": {
  553. "field": "actors",
  554. "size": 5
  555. }
  556. }
  557. }
  558. }
  559. }
  560. }
  561. --------------------------------------------------
  562. Even though the number of actors may be comparatively small and we want only 50 result buckets there is a combinatorial explosion of buckets
  563. during calculation - a single actor can produce n² buckets where n is the number of actors. The sane option would be to first determine
  564. the 10 most popular actors and only then examine the top co-stars for these 10 actors. This alternative strategy is what we call the `breadth_first` collection
  565. mode as opposed to the `depth_first` mode.
  566. NOTE: The `breadth_first` is the default mode for fields with a cardinality bigger than the requested size or when the cardinality is unknown (numeric fields or scripts for instance).
  567. It is possible to override the default heuristic and to provide a collect mode directly in the request:
  568. [source,console,id=terms-aggregation-breadth-first-example]
  569. --------------------------------------------------
  570. GET /_search
  571. {
  572. "aggs": {
  573. "actors": {
  574. "terms": {
  575. "field": "actors",
  576. "size": 10,
  577. "collect_mode": "breadth_first" <1>
  578. },
  579. "aggs": {
  580. "costars": {
  581. "terms": {
  582. "field": "actors",
  583. "size": 5
  584. }
  585. }
  586. }
  587. }
  588. }
  589. }
  590. --------------------------------------------------
  591. <1> the possible values are `breadth_first` and `depth_first`
  592. When using `breadth_first` mode the set of documents that fall into the uppermost buckets are
  593. cached for subsequent replay so there is a memory overhead in doing this which is linear with the number of matching documents.
  594. Note that the `order` parameter can still be used to refer to data from a child aggregation when using the `breadth_first` setting - the parent
  595. aggregation understands that this child aggregation will need to be called first before any of the other child aggregations.
  596. WARNING: Nested aggregations such as `top_hits` which require access to score information under an aggregation that uses the `breadth_first`
  597. collection mode need to replay the query on the second pass but only for the documents belonging to the top buckets.
  598. [[search-aggregations-bucket-terms-aggregation-execution-hint]]
  599. ==== Execution hint
  600. There are different mechanisms by which terms aggregations can be executed:
  601. - by using field values directly in order to aggregate data per-bucket (`map`)
  602. - by using global ordinals of the field and allocating one bucket per global ordinal (`global_ordinals`)
  603. Elasticsearch tries to have sensible defaults so this is something that generally doesn't need to be configured.
  604. `global_ordinals` is the default option for `keyword` field, it uses global ordinals to allocates buckets dynamically
  605. so memory usage is linear to the number of values of the documents that are part of the aggregation scope.
  606. `map` should only be considered when very few documents match a query. Otherwise the ordinals-based execution mode
  607. is significantly faster. By default, `map` is only used when running an aggregation on scripts, since they don't have
  608. ordinals.
  609. [source,console,id=terms-aggregation-execution-hint-example]
  610. --------------------------------------------------
  611. GET /_search
  612. {
  613. "aggs": {
  614. "tags": {
  615. "terms": {
  616. "field": "tags",
  617. "execution_hint": "map" <1>
  618. }
  619. }
  620. }
  621. }
  622. --------------------------------------------------
  623. <1> The possible values are `map`, `global_ordinals`
  624. Please note that Elasticsearch will ignore this execution hint if it is not applicable and that there is no backward compatibility guarantee on these hints.
  625. ==== Missing value
  626. The `missing` parameter defines how documents that are missing a value should be treated.
  627. By default they will be ignored but it is also possible to treat them as if they
  628. had a value.
  629. [source,console,id=terms-aggregation-missing-example]
  630. --------------------------------------------------
  631. GET /_search
  632. {
  633. "aggs": {
  634. "tags": {
  635. "terms": {
  636. "field": "tags",
  637. "missing": "N/A" <1>
  638. }
  639. }
  640. }
  641. }
  642. --------------------------------------------------
  643. <1> Documents without a value in the `tags` field will fall into the same bucket as documents that have the value `N/A`.
  644. ==== Mixing field types
  645. WARNING: When aggregating on multiple indices the type of the aggregated field may not be the same in all indices.
  646. Some types are compatible with each other (`integer` and `long` or `float` and `double`) but when the types are a mix
  647. of decimal and non-decimal number the terms aggregation will promote the non-decimal numbers to decimal numbers.
  648. This can result in a loss of precision in the bucket values.