terms-aggregation.asciidoc 34 KB

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