terms-aggregation.asciidoc 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828
  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,console]
  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", "product": "Product B"}
  28. {"index":{"_id":2}}
  29. {"genre": "rock", "product": "Product C"}
  30. {"index":{"_id":3}}
  31. {"genre": "jazz", "product": "Product D"}
  32. {"index":{"_id":4}}
  33. {"genre": "jazz", "product": "Product E"}
  34. {"index":{"_id":5}}
  35. {"genre": "electronic", "product": "Anthology A"}
  36. {"index":{"_id":6}}
  37. {"genre": "electronic", "product": "Anthology A"}
  38. {"index":{"_id":7}}
  39. {"genre": "electronic", "product": "Product F"}
  40. {"index":{"_id":8}}
  41. {"genre": "electronic", "product": "Product G"}
  42. {"index":{"_id":9}}
  43. {"genre": "electronic", "product": "Product H"}
  44. {"index":{"_id":10}}
  45. {"genre": "electronic", "product": "Product I"}
  46. -------------------------------------------------
  47. // TESTSETUP
  48. //////////////////////////
  49. Example:
  50. [source,console,id=terms-aggregation-example]
  51. --------------------------------------------------
  52. GET /_search
  53. {
  54. "aggs": {
  55. "genres": {
  56. "terms": { "field": "genre" }
  57. }
  58. }
  59. }
  60. --------------------------------------------------
  61. // TEST[s/_search/_search\?filter_path=aggregations/]
  62. Response:
  63. [source,console-result]
  64. --------------------------------------------------
  65. {
  66. ...
  67. "aggregations": {
  68. "genres": {
  69. "doc_count_error_upper_bound": 0, <1>
  70. "sum_other_doc_count": 0, <2>
  71. "buckets": [ <3>
  72. {
  73. "key": "electronic",
  74. "doc_count": 6
  75. },
  76. {
  77. "key": "rock",
  78. "doc_count": 3
  79. },
  80. {
  81. "key": "jazz",
  82. "doc_count": 2
  83. }
  84. ]
  85. }
  86. }
  87. }
  88. --------------------------------------------------
  89. // TESTRESPONSE[s/\.\.\.//]
  90. <1> an upper bound of the error on the document counts for each term, see <<terms-agg-doc-count-error,below>>
  91. <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
  92. <3> the list of the top buckets, the meaning of `top` being defined by the <<search-aggregations-bucket-terms-aggregation-order,order>>
  93. [[search-aggregations-bucket-terms-aggregation-types]]
  94. The `field` can be <<keyword>>, <<number>>, <<ip, `ip`>>, <<boolean, `boolean`>>,
  95. or <<binary, `binary`>>.
  96. NOTE: By default, you cannot run a `terms` aggregation on a `text` field. Use a
  97. `keyword` <<multi-fields,sub-field>> instead. Alternatively, you can enable
  98. <<fielddata,`fielddata`>> on the `text` field to create buckets for the field's
  99. <<analysis,analyzed>> terms. Enabling `fielddata` can significantly increase
  100. memory usage.
  101. [[search-aggregations-bucket-terms-aggregation-size]]
  102. ==== Size
  103. By default, the `terms` aggregation returns the top ten terms with the most
  104. documents. Use the `size` parameter to return more terms, up to the
  105. <<search-settings-max-buckets,search.max_buckets>> limit.
  106. If your data contains 100 or 1000 unique terms, you can increase the `size` of
  107. the `terms` aggregation to return them all. If you have more unique terms and
  108. you need them all, use the
  109. <<search-aggregations-bucket-composite-aggregation,composite aggregation>>
  110. instead.
  111. Larger values of `size` use more memory to compute and, push the whole
  112. aggregation close to the `max_buckets` limit. You'll know you've gone too large
  113. if the request fails with a message about `max_buckets`.
  114. [[search-aggregations-bucket-terms-aggregation-shard-size]]
  115. ==== Shard Size
  116. To get more accurate results, the `terms` agg fetches more than
  117. the top `size` terms from each shard. It fetches the top `shard_size` terms,
  118. which defaults to `size * 1.5 + 10`.
  119. This is to handle the case when one term has many documents on one shard but is
  120. just below the `size` threshold on all other shards. If each shard only
  121. returned `size` terms, the aggregation would return an partial doc count for
  122. the term. So `terms` returns more terms in an attempt to catch the missing
  123. terms. This helps, but it's still quite possible to return a partial doc
  124. count for a term. It just takes a term with more disparate per-shard doc counts.
  125. You can increase `shard_size` to better account for these disparate doc counts
  126. and improve the accuracy of the selection of top terms. It is much cheaper to increase
  127. the `shard_size` than to increase the `size`. However, it still takes more
  128. bytes over the wire and waiting in memory on the coordinating node.
  129. IMPORTANT: This guidance only applies if you're using the `terms` aggregation's
  130. default sort `order`. If you're sorting by anything other than document count in
  131. descending order, see <<search-aggregations-bucket-terms-aggregation-order>>.
  132. NOTE: `shard_size` cannot be smaller than `size` (as it doesn't make much sense). When it is, Elasticsearch will
  133. override it and reset it to be equal to `size`.
  134. [[terms-agg-doc-count-error]]
  135. ==== Document count error
  136. `sum_other_doc_count` is the number of documents that didn't make it into the
  137. the top `size` terms. If this is greater than `0`, you can be sure that the
  138. `terms` agg had to throw away some buckets, either because they didn't fit into
  139. `size` on the coordinating node or they didn't fit into `shard_size` on the
  140. data node.
  141. ==== Per bucket document count error
  142. If you set the `show_term_doc_count_error` parameter to `true`, the `terms`
  143. aggregation will include `doc_count_error_upper_bound`, which is an upper bound
  144. to the error on the `doc_count` returned by each shard. It's the
  145. sum of the size of the largest bucket on each shard that didn't fit into
  146. `shard_size`.
  147. In more concrete terms, imagine there is one bucket that is very large on one
  148. shard and just outside the `shard_size` on all the other shards. In that case,
  149. the `terms` agg will return the bucket because it is large, but it'll be missing
  150. data from many documents on the shards where the term fell below the `shard_size` threshold.
  151. `doc_count_error_upper_bound` is the maximum number of those missing documents.
  152. [source,console,id=terms-aggregation-doc-count-error-example]
  153. --------------------------------------------------
  154. GET /_search
  155. {
  156. "aggs": {
  157. "products": {
  158. "terms": {
  159. "field": "product",
  160. "size": 5,
  161. "show_term_doc_count_error": true
  162. }
  163. }
  164. }
  165. }
  166. --------------------------------------------------
  167. // TEST[s/_search/_search\?filter_path=aggregations/]
  168. These errors can only be calculated in this way when the terms are ordered by descending document count. When the aggregation is
  169. ordered by the terms values themselves (either ascending or descending) there is no error in the document count since if a shard
  170. 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
  171. aggregation is either sorted by a sub aggregation or in order of ascending document count, the error in the document counts cannot be
  172. determined and is given a value of -1 to indicate this.
  173. [[search-aggregations-bucket-terms-aggregation-order]]
  174. ==== Order
  175. By default, the `terms` aggregation orders terms by descending document `_count`.
  176. Use the `order` parameter to specify a different sort order.
  177. WARNING: Avoid using `"order": { "_count": "asc" }`. If you need to find rare
  178. terms, use the
  179. <<search-aggregations-bucket-rare-terms-aggregation,`rare_terms`>> aggregation
  180. instead. Due to the way the `terms` aggregation
  181. <<search-aggregations-bucket-terms-aggregation-shard-size,gets terms from
  182. shards>>, sorting by ascending doc count often produces inaccurate results.
  183. If you really must, this is how you sort on doc count ascending:
  184. [source,console,id=terms-aggregation-count-example]
  185. --------------------------------------------------
  186. GET /_search
  187. {
  188. "aggs": {
  189. "genres": {
  190. "terms": {
  191. "field": "genre",
  192. "order": { "_count": "asc" }
  193. }
  194. }
  195. }
  196. }
  197. --------------------------------------------------
  198. Ordering the buckets alphabetically by their terms in an ascending manner:
  199. [source,console,id=terms-aggregation-asc-example]
  200. --------------------------------------------------
  201. GET /_search
  202. {
  203. "aggs": {
  204. "genres": {
  205. "terms": {
  206. "field": "genre",
  207. "order": { "_key": "asc" }
  208. }
  209. }
  210. }
  211. }
  212. --------------------------------------------------
  213. WARNING: Test any sorts on sub-aggregations before using them in production.
  214. Sorting on a sub-aggregation may return errors or inaccurate results. For
  215. example, due to the way the `terms` aggregation
  216. <<search-aggregations-bucket-terms-aggregation-shard-size,gets results from
  217. shards>>, sorting on a `max` sub-aggregation in _ascending_ order often produces
  218. inaccurate results. However, sorting on a `max` sub-aggregation in _descending_
  219. order is typically safe.
  220. Ordering the buckets by single value metrics sub-aggregation (identified by the aggregation name):
  221. [source,console,id=terms-aggregation-subaggregation-example]
  222. --------------------------------------------------
  223. GET /_search
  224. {
  225. "aggs": {
  226. "genres": {
  227. "terms": {
  228. "field": "genre",
  229. "order": { "max_play_count": "desc" }
  230. },
  231. "aggs": {
  232. "max_play_count": { "max": { "field": "play_count" } }
  233. }
  234. }
  235. }
  236. }
  237. --------------------------------------------------
  238. Ordering the buckets by multi value metrics sub-aggregation (identified by the aggregation name):
  239. [source,console,id=terms-aggregation-multivalue-subaggregation-example]
  240. --------------------------------------------------
  241. GET /_search
  242. {
  243. "aggs": {
  244. "genres": {
  245. "terms": {
  246. "field": "genre",
  247. "order": { "playback_stats.max": "desc" }
  248. },
  249. "aggs": {
  250. "playback_stats": { "stats": { "field": "play_count" } }
  251. }
  252. }
  253. }
  254. }
  255. --------------------------------------------------
  256. [NOTE]
  257. .Pipeline aggs cannot be used for sorting
  258. =======================================
  259. <<search-aggregations-pipeline,Pipeline aggregations>> are run during the
  260. reduce phase after all other aggregations have already completed. For this
  261. reason, they cannot be used for ordering.
  262. =======================================
  263. It is also possible to order the buckets based on a "deeper" aggregation in the hierarchy. This is supported as long
  264. as the aggregations path are of a single-bucket type, where the last aggregation in the path may either be a single-bucket
  265. 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`),
  266. 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
  267. a multi-value metrics aggregation, and in case of a single-value metrics aggregation the sort will be applied on that value).
  268. The path must be defined in the following form:
  269. // {wikipedia}/Extended_Backus%E2%80%93Naur_Form
  270. [source,ebnf]
  271. --------------------------------------------------
  272. AGG_SEPARATOR = '>' ;
  273. METRIC_SEPARATOR = '.' ;
  274. AGG_NAME = <the name of the aggregation> ;
  275. METRIC = <the name of the metric (in case of multi-value metrics aggregation)> ;
  276. PATH = <AGG_NAME> [ <AGG_SEPARATOR>, <AGG_NAME> ]* [ <METRIC_SEPARATOR>, <METRIC> ] ;
  277. --------------------------------------------------
  278. [source,console,id=terms-aggregation-hierarchy-example]
  279. --------------------------------------------------
  280. GET /_search
  281. {
  282. "aggs": {
  283. "countries": {
  284. "terms": {
  285. "field": "artist.country",
  286. "order": { "rock>playback_stats.avg": "desc" }
  287. },
  288. "aggs": {
  289. "rock": {
  290. "filter": { "term": { "genre": "rock" } },
  291. "aggs": {
  292. "playback_stats": { "stats": { "field": "play_count" } }
  293. }
  294. }
  295. }
  296. }
  297. }
  298. }
  299. --------------------------------------------------
  300. The above will sort the artist's countries buckets based on the average play count among the rock songs.
  301. Multiple criteria can be used to order the buckets by providing an array of order criteria such as the following:
  302. [source,console,id=terms-aggregation-multicriteria-example]
  303. --------------------------------------------------
  304. GET /_search
  305. {
  306. "aggs": {
  307. "countries": {
  308. "terms": {
  309. "field": "artist.country",
  310. "order": [ { "rock>playback_stats.avg": "desc" }, { "_count": "desc" } ]
  311. },
  312. "aggs": {
  313. "rock": {
  314. "filter": { "term": { "genre": "rock" } },
  315. "aggs": {
  316. "playback_stats": { "stats": { "field": "play_count" } }
  317. }
  318. }
  319. }
  320. }
  321. }
  322. }
  323. --------------------------------------------------
  324. The above will sort the artist's countries buckets based on the average play count among the rock songs and then by
  325. their `doc_count` in descending order.
  326. NOTE: In the event that two buckets share the same values for all order criteria the bucket's term value is used as a
  327. tie-breaker in ascending alphabetical order to prevent non-deterministic ordering of buckets.
  328. ==== Minimum document count
  329. It is possible to only return terms that match more than a configured number of hits using the `min_doc_count` option:
  330. [source,console,id=terms-aggregation-min-doc-count-example]
  331. --------------------------------------------------
  332. GET /_search
  333. {
  334. "aggs": {
  335. "tags": {
  336. "terms": {
  337. "field": "tags",
  338. "min_doc_count": 10
  339. }
  340. }
  341. }
  342. }
  343. --------------------------------------------------
  344. The above aggregation would only return tags which have been found in 10 hits or more. Default value is `1`.
  345. 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.
  346. [[search-aggregations-bucket-terms-shard-min-doc-count]]
  347. ===== `shard_min_doc_count`
  348. // tag::min-doc-count[]
  349. 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.
  350. // end::min-doc-count[]
  351. NOTE: Setting `min_doc_count`=`0` will also return buckets for terms that didn't match any hit. However, some of
  352. the returned terms which have a document count of zero might only belong to deleted documents or documents
  353. from other types, so there is no warranty that a `match_all` query would find a positive document count for
  354. those terms.
  355. WARNING: When NOT sorting on `doc_count` descending, high values of `min_doc_count` may return a number of buckets
  356. which is less than `size` because not enough data was gathered from the shards. Missing buckets can be
  357. back by increasing `shard_size`.
  358. 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`.
  359. [[search-aggregations-bucket-terms-aggregation-script]]
  360. ==== Script
  361. Use a <<runtime,runtime field>> if the data in your documents doesn't
  362. exactly match what you'd like to aggregate. If, for example, "anthologies"
  363. need to be in a special category then you could run this:
  364. [source,console,id=terms-aggregation-script-example]
  365. --------------------------------------------------
  366. GET /_search
  367. {
  368. "size": 0,
  369. "runtime_mappings": {
  370. "normalized_genre": {
  371. "type": "keyword",
  372. "script": """
  373. String genre = doc['genre'].value;
  374. if (doc['product'].value.startsWith('Anthology')) {
  375. emit(genre + ' anthology');
  376. } else {
  377. emit(genre);
  378. }
  379. """
  380. }
  381. },
  382. "aggs": {
  383. "genres": {
  384. "terms": {
  385. "field": "normalized_genre"
  386. }
  387. }
  388. }
  389. }
  390. --------------------------------------------------
  391. Which will look like:
  392. [source,console-result]
  393. --------------------------------------------------
  394. {
  395. "aggregations": {
  396. "genres": {
  397. "doc_count_error_upper_bound": 0,
  398. "sum_other_doc_count": 0,
  399. "buckets": [
  400. {
  401. "key": "electronic",
  402. "doc_count": 4
  403. },
  404. {
  405. "key": "rock",
  406. "doc_count": 3
  407. },
  408. {
  409. "key": "electronic anthology",
  410. "doc_count": 2
  411. },
  412. {
  413. "key": "jazz",
  414. "doc_count": 2
  415. }
  416. ]
  417. }
  418. },
  419. ...
  420. }
  421. --------------------------------------------------
  422. // TESTRESPONSE[s/\.\.\./"took": "$body.took", "timed_out": false, "_shards": "$body._shards", "hits": "$body.hits"/]
  423. This is a little slower because the runtime field has to access two fields
  424. instead of one and because there are some optimizations that work on
  425. non-runtime `keyword` fields that we have to give up for for runtime
  426. `keyword` fields. If you need the speed, you can index the
  427. `normalized_genre` field.
  428. // TODO when we have calculated fields we can link to them here.
  429. ==== Filtering Values
  430. It is possible to filter the values for which buckets will be created. This can be done using the `include` and
  431. `exclude` parameters which are based on regular expression strings or arrays of exact values. Additionally,
  432. `include` clauses can filter using `partition` expressions.
  433. ===== Filtering Values with regular expressions
  434. [source,console,id=terms-aggregation-regex-example]
  435. --------------------------------------------------
  436. GET /_search
  437. {
  438. "aggs": {
  439. "tags": {
  440. "terms": {
  441. "field": "tags",
  442. "include": ".*sport.*",
  443. "exclude": "water_.*"
  444. }
  445. }
  446. }
  447. }
  448. --------------------------------------------------
  449. In the above example, buckets will be created for all the tags that has the word `sport` in them, except those starting
  450. with `water_` (so the tag `water_sports` will not be aggregated). The `include` regular expression will determine what
  451. values are "allowed" to be aggregated, while the `exclude` determines the values that should not be aggregated. When
  452. both are defined, the `exclude` has precedence, meaning, the `include` is evaluated first and only then the `exclude`.
  453. The syntax is the same as <<regexp-syntax,regexp queries>>.
  454. ===== Filtering Values with exact values
  455. For matching based on exact values the `include` and `exclude` parameters can simply take an array of
  456. strings that represent the terms as they are found in the index:
  457. [source,console,id=terms-aggregation-exact-example]
  458. --------------------------------------------------
  459. GET /_search
  460. {
  461. "aggs": {
  462. "JapaneseCars": {
  463. "terms": {
  464. "field": "make",
  465. "include": [ "mazda", "honda" ]
  466. }
  467. },
  468. "ActiveCarManufacturers": {
  469. "terms": {
  470. "field": "make",
  471. "exclude": [ "rover", "jensen" ]
  472. }
  473. }
  474. }
  475. }
  476. --------------------------------------------------
  477. ===== Filtering Values with partitions
  478. Sometimes there are too many unique terms to process in a single request/response pair so
  479. it can be useful to break the analysis up into multiple requests.
  480. This can be achieved by grouping the field's values into a number of partitions at query-time and processing
  481. only one partition in each request.
  482. Consider this request which is looking for accounts that have not logged any access recently:
  483. [source,console,id=terms-aggregation-partitions-example]
  484. --------------------------------------------------
  485. GET /_search
  486. {
  487. "size": 0,
  488. "aggs": {
  489. "expired_sessions": {
  490. "terms": {
  491. "field": "account_id",
  492. "include": {
  493. "partition": 0,
  494. "num_partitions": 20
  495. },
  496. "size": 10000,
  497. "order": {
  498. "last_access": "asc"
  499. }
  500. },
  501. "aggs": {
  502. "last_access": {
  503. "max": {
  504. "field": "access_date"
  505. }
  506. }
  507. }
  508. }
  509. }
  510. }
  511. --------------------------------------------------
  512. This request is finding the last logged access date for a subset of customer accounts because we
  513. might want to expire some customer accounts who haven't been seen for a long while.
  514. The `num_partitions` setting has requested that the unique account_ids are organized evenly into twenty
  515. partitions (0 to 19). and the `partition` setting in this request filters to only consider account_ids falling
  516. into partition 0. Subsequent requests should ask for partitions 1 then 2 etc to complete the expired-account analysis.
  517. Note that the `size` setting for the number of results returned needs to be tuned with the `num_partitions`.
  518. For this particular account-expiration example the process for balancing values for `size` and `num_partitions` would be as follows:
  519. 1. Use the `cardinality` aggregation to estimate the total number of unique account_id values
  520. 2. Pick a value for `num_partitions` to break the number from 1) up into more manageable chunks
  521. 3. Pick a `size` value for the number of responses we want from each partition
  522. 4. Run a test request
  523. If we have a circuit-breaker error we are trying to do too much in one request and must increase `num_partitions`.
  524. If the request was successful but the last account ID in the date-sorted test response was still an account we might want to
  525. expire then we may be missing accounts of interest and have set our numbers too low. We must either
  526. * increase the `size` parameter to return more results per partition (could be heavy on memory) or
  527. * increase the `num_partitions` to consider less accounts per request (could increase overall processing time as we need to make more requests)
  528. Ultimately this is a balancing act between managing the Elasticsearch resources required to process a single request and the volume
  529. of requests that the client application must issue to complete a task.
  530. WARNING: Partitions cannot be used together with an `exclude` parameter.
  531. ==== Multi-field terms aggregation
  532. The `terms` aggregation does not support collecting terms from multiple fields
  533. in the same document. The reason is that the `terms` agg doesn't collect the
  534. string term values themselves, but rather uses
  535. <<search-aggregations-bucket-terms-aggregation-execution-hint,global ordinals>>
  536. to produce a list of all of the unique values in the field. Global ordinals
  537. results in an important performance boost which would not be possible across
  538. multiple fields.
  539. There are three approaches that you can use to perform a `terms` agg across
  540. multiple fields:
  541. <<search-aggregations-bucket-terms-aggregation-script,Script>>::
  542. Use a script to retrieve terms from multiple fields. This disables the global
  543. ordinals optimization and will be slower than collecting terms from a single
  544. field, but it gives you the flexibility to implement this option at search
  545. time.
  546. <<copy-to,`copy_to` field>>::
  547. If you know ahead of time that you want to collect the terms from two or more
  548. fields, then use `copy_to` in your mapping to create a new dedicated field at
  549. index time which contains the values from both fields. You can aggregate on
  550. this single field, which will benefit from the global ordinals optimization.
  551. <<search-aggregations-bucket-multi-terms-aggregation, `multi_terms` aggregation>>::
  552. Use multi_terms aggregation to combine terms from multiple fields into a compound key. This
  553. also disables the global ordinals and will be slower than collecting terms from a single field.
  554. It is faster but less flexible than using a script.
  555. [[search-aggregations-bucket-terms-aggregation-collect]]
  556. ==== Collect mode
  557. Deferring calculation of child aggregations
  558. For fields with many unique terms and a small number of required results it can be more efficient to delay the calculation
  559. of child aggregations until the top parent-level aggs have been pruned. Ordinarily, all branches of the aggregation tree
  560. are expanded in one depth-first pass and only then any pruning occurs.
  561. In some scenarios this can be very wasteful and can hit memory constraints.
  562. An example problem scenario is querying a movie database for the 10 most popular actors and their 5 most common co-stars:
  563. [source,console,id=terms-aggregation-collect-mode-example]
  564. --------------------------------------------------
  565. GET /_search
  566. {
  567. "aggs": {
  568. "actors": {
  569. "terms": {
  570. "field": "actors",
  571. "size": 10
  572. },
  573. "aggs": {
  574. "costars": {
  575. "terms": {
  576. "field": "actors",
  577. "size": 5
  578. }
  579. }
  580. }
  581. }
  582. }
  583. }
  584. --------------------------------------------------
  585. Even though the number of actors may be comparatively small and we want only 50 result buckets there is a combinatorial explosion of buckets
  586. during calculation - a single actor can produce n² buckets where n is the number of actors. The sane option would be to first determine
  587. 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
  588. mode as opposed to the `depth_first` mode.
  589. 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).
  590. It is possible to override the default heuristic and to provide a collect mode directly in the request:
  591. [source,console,id=terms-aggregation-breadth-first-example]
  592. --------------------------------------------------
  593. GET /_search
  594. {
  595. "aggs": {
  596. "actors": {
  597. "terms": {
  598. "field": "actors",
  599. "size": 10,
  600. "collect_mode": "breadth_first" <1>
  601. },
  602. "aggs": {
  603. "costars": {
  604. "terms": {
  605. "field": "actors",
  606. "size": 5
  607. }
  608. }
  609. }
  610. }
  611. }
  612. }
  613. --------------------------------------------------
  614. <1> the possible values are `breadth_first` and `depth_first`
  615. When using `breadth_first` mode the set of documents that fall into the uppermost buckets are
  616. cached for subsequent replay so there is a memory overhead in doing this which is linear with the number of matching documents.
  617. 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
  618. aggregation understands that this child aggregation will need to be called first before any of the other child aggregations.
  619. WARNING: Nested aggregations such as `top_hits` which require access to score information under an aggregation that uses the `breadth_first`
  620. collection mode need to replay the query on the second pass but only for the documents belonging to the top buckets.
  621. [[search-aggregations-bucket-terms-aggregation-execution-hint]]
  622. ==== Execution hint
  623. There are different mechanisms by which terms aggregations can be executed:
  624. - by using field values directly in order to aggregate data per-bucket (`map`)
  625. - by using global ordinals of the field and allocating one bucket per global ordinal (`global_ordinals`)
  626. Elasticsearch tries to have sensible defaults so this is something that generally doesn't need to be configured.
  627. `global_ordinals` is the default option for `keyword` field, it uses global ordinals to allocates buckets dynamically
  628. so memory usage is linear to the number of values of the documents that are part of the aggregation scope.
  629. `map` should only be considered when very few documents match a query. Otherwise the ordinals-based execution mode
  630. is significantly faster. By default, `map` is only used when running an aggregation on scripts, since they don't have
  631. ordinals.
  632. [source,console,id=terms-aggregation-execution-hint-example]
  633. --------------------------------------------------
  634. GET /_search
  635. {
  636. "aggs": {
  637. "tags": {
  638. "terms": {
  639. "field": "tags",
  640. "execution_hint": "map" <1>
  641. }
  642. }
  643. }
  644. }
  645. --------------------------------------------------
  646. <1> The possible values are `map`, `global_ordinals`
  647. 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.
  648. ==== Missing value
  649. The `missing` parameter defines how documents that are missing a value should be treated.
  650. By default they will be ignored but it is also possible to treat them as if they
  651. had a value.
  652. [source,console,id=terms-aggregation-missing-example]
  653. --------------------------------------------------
  654. GET /_search
  655. {
  656. "aggs": {
  657. "tags": {
  658. "terms": {
  659. "field": "tags",
  660. "missing": "N/A" <1>
  661. }
  662. }
  663. }
  664. }
  665. --------------------------------------------------
  666. <1> Documents without a value in the `tags` field will fall into the same bucket as documents that have the value `N/A`.
  667. ==== Mixing field types
  668. WARNING: When aggregating on multiple indices the type of the aggregated field may not be the same in all indices.
  669. Some types are compatible with each other (`integer` and `long` or `float` and `double`) but when the types are a mix
  670. of decimal and non-decimal number the terms aggregation will promote the non-decimal numbers to decimal numbers.
  671. This can result in a loss of precision in the bucket values.
  672. [discrete]
  673. [[search-aggregations-bucket-terms-aggregation-troubleshooting]]
  674. ==== Troubleshooting
  675. ===== Failed Trying to Format Bytes
  676. When running a terms aggregation (or other aggregation, but in practice usually
  677. terms) over multiple indices, you may get an error that starts with "Failed
  678. trying to format bytes...". This is usually caused by two of the indices not
  679. having the same mapping type for the field being aggregated.
  680. **Use an explicit `value_type`**
  681. Although it's best to correct the mappings, you can work around this issue if
  682. the field is unmapped in one of the indices. Setting the `value_type` parameter
  683. can resolve the issue by coercing the unmapped field into the correct type.
  684. [source,console,id=terms-aggregation-value_type-example]
  685. ----
  686. GET /_search
  687. {
  688. "aggs": {
  689. "ip_addresses": {
  690. "terms": {
  691. "field": "destination_ip",
  692. "missing": "0.0.0.0",
  693. "value_type": "ip"
  694. }
  695. }
  696. }
  697. }
  698. ----