composite-aggregation.asciidoc 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714
  1. [[search-aggregations-bucket-composite-aggregation]]
  2. === Composite aggregation
  3. A multi-bucket aggregation that creates composite buckets from different sources.
  4. Unlike the other `multi-bucket` aggregation the `composite` aggregation can be used
  5. to paginate **all** buckets from a multi-level aggregation efficiently. This aggregation
  6. provides a way to stream **all** buckets of a specific aggregation similarly to what
  7. <<request-body-search-scroll, scroll>> does for documents.
  8. The composite buckets are built from the combinations of the
  9. values extracted/created for each document and each combination is considered as
  10. a composite bucket.
  11. //////////////////////////
  12. [source,js]
  13. --------------------------------------------------
  14. PUT /sales
  15. {
  16. "mappings": {
  17. "properties": {
  18. "product": {
  19. "type": "keyword"
  20. },
  21. "timestamp": {
  22. "type": "date"
  23. },
  24. "price": {
  25. "type": "long"
  26. },
  27. "shop": {
  28. "type": "keyword"
  29. },
  30. "nested": {
  31. "type": "nested",
  32. "properties": {
  33. "product": {
  34. "type": "keyword"
  35. },
  36. "timestamp": {
  37. "type": "date"
  38. },
  39. "price": {
  40. "type": "long"
  41. },
  42. "shop": {
  43. "type": "keyword"
  44. }
  45. }
  46. }
  47. }
  48. }
  49. }
  50. POST /sales/_bulk?refresh
  51. {"index":{"_id":0}}
  52. {"product": "mad max", "price": "20", "timestamp": "2017-05-09T14:35"}
  53. {"index":{"_id":1}}
  54. {"product": "mad max", "price": "25", "timestamp": "2017-05-09T12:35"}
  55. {"index":{"_id":2}}
  56. {"product": "rocky", "price": "10", "timestamp": "2017-05-08T09:10"}
  57. {"index":{"_id":3}}
  58. {"product": "mad max", "price": "27", "timestamp": "2017-05-10T07:07"}
  59. {"index":{"_id":4}}
  60. {"product": "apocalypse now", "price": "10", "timestamp": "2017-05-11T08:35"}
  61. -------------------------------------------------
  62. // NOTCONSOLE
  63. // TESTSETUP
  64. //////////////////////////
  65. For instance the following document:
  66. [source,js]
  67. --------------------------------------------------
  68. {
  69. "keyword": ["foo", "bar"],
  70. "number": [23, 65, 76]
  71. }
  72. --------------------------------------------------
  73. // NOTCONSOLE
  74. \... creates the following composite buckets when `keyword` and `number` are used as values source
  75. for the aggregation:
  76. [source,js]
  77. --------------------------------------------------
  78. { "keyword": "foo", "number": 23 }
  79. { "keyword": "foo", "number": 65 }
  80. { "keyword": "foo", "number": 76 }
  81. { "keyword": "bar", "number": 23 }
  82. { "keyword": "bar", "number": 65 }
  83. { "keyword": "bar", "number": 76 }
  84. --------------------------------------------------
  85. // NOTCONSOLE
  86. ==== Values source
  87. The `sources` parameter controls the sources that should be used to build the composite buckets.
  88. The order that the `sources` are defined is important because it also controls the order
  89. the keys are returned.
  90. The name given to each sources must be unique.
  91. There are three different types of values source:
  92. [[_terms]]
  93. ===== Terms
  94. The `terms` value source is equivalent to a simple `terms` aggregation.
  95. The values are extracted from a field or a script exactly like the `terms` aggregation.
  96. Example:
  97. [source,console,id=composite-aggregation-terms-field-example]
  98. --------------------------------------------------
  99. GET /_search
  100. {
  101. "size": 0,
  102. "aggs" : {
  103. "my_buckets": {
  104. "composite" : {
  105. "sources" : [
  106. { "product": { "terms" : { "field": "product" } } }
  107. ]
  108. }
  109. }
  110. }
  111. }
  112. --------------------------------------------------
  113. Like the `terms` aggregation it is also possible to use a script to create the values for the composite buckets:
  114. [source,console,id=composite-aggregation-terms-script-example]
  115. --------------------------------------------------
  116. GET /_search
  117. {
  118. "size": 0,
  119. "aggs" : {
  120. "my_buckets": {
  121. "composite" : {
  122. "sources" : [
  123. {
  124. "product": {
  125. "terms" : {
  126. "script" : {
  127. "source": "doc['product'].value",
  128. "lang": "painless"
  129. }
  130. }
  131. }
  132. }
  133. ]
  134. }
  135. }
  136. }
  137. }
  138. --------------------------------------------------
  139. [[_histogram]]
  140. ===== Histogram
  141. The `histogram` value source can be applied on numeric values to build fixed size
  142. interval over the values. The `interval` parameter defines how the numeric values should be
  143. transformed. For instance an `interval` set to 5 will translate any numeric values to its closest interval,
  144. a value of `101` would be translated to `100` which is the key for the interval between 100 and 105.
  145. Example:
  146. [source,console,id=composite-aggregation-histogram-field-example]
  147. --------------------------------------------------
  148. GET /_search
  149. {
  150. "size": 0,
  151. "aggs" : {
  152. "my_buckets": {
  153. "composite" : {
  154. "sources" : [
  155. { "histo": { "histogram" : { "field": "price", "interval": 5 } } }
  156. ]
  157. }
  158. }
  159. }
  160. }
  161. --------------------------------------------------
  162. The values are built from a numeric field or a script that return numerical values:
  163. [source,console,id=composite-aggregation-histogram-script-example]
  164. --------------------------------------------------
  165. GET /_search
  166. {
  167. "size": 0,
  168. "aggs" : {
  169. "my_buckets": {
  170. "composite" : {
  171. "sources" : [
  172. {
  173. "histo": {
  174. "histogram" : {
  175. "interval": 5,
  176. "script" : {
  177. "source": "doc['price'].value",
  178. "lang": "painless"
  179. }
  180. }
  181. }
  182. }
  183. ]
  184. }
  185. }
  186. }
  187. }
  188. --------------------------------------------------
  189. [[_date_histogram]]
  190. ===== Date histogram
  191. The `date_histogram` is similar to the `histogram` value source except that the interval
  192. is specified by date/time expression:
  193. [source,console,id=composite-aggregation-datehistogram-example]
  194. --------------------------------------------------
  195. GET /_search
  196. {
  197. "size": 0,
  198. "aggs" : {
  199. "my_buckets": {
  200. "composite" : {
  201. "sources" : [
  202. { "date": { "date_histogram" : { "field": "timestamp", "calendar_interval": "1d" } } }
  203. ]
  204. }
  205. }
  206. }
  207. }
  208. --------------------------------------------------
  209. The example above creates an interval per day and translates all `timestamp` values to the start of its closest intervals.
  210. Available expressions for interval: `year`, `quarter`, `month`, `week`, `day`, `hour`, `minute`, `second`
  211. Time values can also be specified via abbreviations supported by <<time-units,time units>> parsing.
  212. Note that fractional time values are not supported, but you can address this by shifting to another
  213. time unit (e.g., `1.5h` could instead be specified as `90m`).
  214. *Format*
  215. Internally, a date is represented as a 64 bit number representing a timestamp in milliseconds-since-the-epoch.
  216. These timestamps are returned as the bucket keys. It is possible to return a formatted date string instead using
  217. the format specified with the format parameter:
  218. [source,console,id=composite-aggregation-datehistogram-format-example]
  219. --------------------------------------------------
  220. GET /_search
  221. {
  222. "size": 0,
  223. "aggs" : {
  224. "my_buckets": {
  225. "composite" : {
  226. "sources" : [
  227. {
  228. "date": {
  229. "date_histogram" : {
  230. "field": "timestamp",
  231. "calendar_interval": "1d",
  232. "format": "yyyy-MM-dd" <1>
  233. }
  234. }
  235. }
  236. ]
  237. }
  238. }
  239. }
  240. }
  241. --------------------------------------------------
  242. <1> Supports expressive date <<date-format-pattern,format pattern>>
  243. *Time Zone*
  244. Date-times are stored in Elasticsearch in UTC. By default, all bucketing and
  245. rounding is also done in UTC. The `time_zone` parameter can be used to indicate
  246. that bucketing should use a different time zone.
  247. Time zones may either be specified as an ISO 8601 UTC offset (e.g. `+01:00` or
  248. `-08:00`) or as a timezone id, an identifier used in the TZ database like
  249. `America/Los_Angeles`.
  250. ===== Mixing different values source
  251. The `sources` parameter accepts an array of values source.
  252. It is possible to mix different values source to create composite buckets.
  253. For example:
  254. [source,console,id=composite-aggregation-mixing-sources-example]
  255. --------------------------------------------------
  256. GET /_search
  257. {
  258. "size": 0,
  259. "aggs" : {
  260. "my_buckets": {
  261. "composite" : {
  262. "sources" : [
  263. { "date": { "date_histogram": { "field": "timestamp", "calendar_interval": "1d" } } },
  264. { "product": { "terms": {"field": "product" } } }
  265. ]
  266. }
  267. }
  268. }
  269. }
  270. --------------------------------------------------
  271. This will create composite buckets from the values created by two values source, a `date_histogram` and a `terms`.
  272. Each bucket is composed of two values, one for each value source defined in the aggregation.
  273. Any type of combinations is allowed and the order in the array is preserved
  274. in the composite buckets.
  275. [source,console,id=composite-aggregation-mixing-three-sources-example]
  276. --------------------------------------------------
  277. GET /_search
  278. {
  279. "size": 0,
  280. "aggs" : {
  281. "my_buckets": {
  282. "composite" : {
  283. "sources" : [
  284. { "shop": { "terms": {"field": "shop" } } },
  285. { "product": { "terms": { "field": "product" } } },
  286. { "date": { "date_histogram": { "field": "timestamp", "calendar_interval": "1d" } } }
  287. ]
  288. }
  289. }
  290. }
  291. }
  292. --------------------------------------------------
  293. ==== Order
  294. By default the composite buckets are sorted by their natural ordering. Values are sorted
  295. in ascending order of their values. When multiple value sources are requested, the ordering is done per value
  296. source, the first value of the composite bucket is compared to the first value of the other composite bucket and if they are equals the
  297. next values in the composite bucket are used for tie-breaking. This means that the composite bucket
  298. `[foo, 100]` is considered smaller than `[foobar, 0]` because `foo` is considered smaller than `foobar`.
  299. It is possible to define the direction of the sort for each value source by setting `order` to `asc` (default value)
  300. or `desc` (descending order) directly in the value source definition.
  301. For example:
  302. [source,console,id=composite-aggregation-order-example]
  303. --------------------------------------------------
  304. GET /_search
  305. {
  306. "size": 0,
  307. "aggs" : {
  308. "my_buckets": {
  309. "composite" : {
  310. "sources" : [
  311. { "date": { "date_histogram": { "field": "timestamp", "calendar_interval": "1d", "order": "desc" } } },
  312. { "product": { "terms": {"field": "product", "order": "asc" } } }
  313. ]
  314. }
  315. }
  316. }
  317. }
  318. --------------------------------------------------
  319. \... will sort the composite bucket in descending order when comparing values from the `date_histogram` source
  320. and in ascending order when comparing values from the `terms` source.
  321. ==== Missing bucket
  322. By default documents without a value for a given source are ignored.
  323. It is possible to include them in the response by setting `missing_bucket` to
  324. `true` (defaults to `false`):
  325. [source,console,id=composite-aggregation-missing-bucket-example]
  326. --------------------------------------------------
  327. GET /_search
  328. {
  329. "size": 0,
  330. "aggs" : {
  331. "my_buckets": {
  332. "composite" : {
  333. "sources" : [
  334. { "product_name": { "terms" : { "field": "product", "missing_bucket": true } } }
  335. ]
  336. }
  337. }
  338. }
  339. }
  340. --------------------------------------------------
  341. In the example above the source `product_name` will emit an explicit `null` value
  342. for documents without a value for the field `product`.
  343. The `order` specified in the source dictates whether the `null` values should rank
  344. first (ascending order, `asc`) or last (descending order, `desc`).
  345. ==== Size
  346. The `size` parameter can be set to define how many composite buckets should be returned.
  347. Each composite bucket is considered as a single bucket so setting a size of 10 will return the
  348. first 10 composite buckets created from the values source.
  349. The response contains the values for each composite bucket in an array containing the values extracted
  350. from each value source.
  351. ==== Pagination
  352. If the number of composite buckets is too high (or unknown) to be returned in a single response
  353. it is possible to split the retrieval in multiple requests.
  354. Since the composite buckets are flat by nature, the requested `size` is exactly the number of composite buckets
  355. that will be returned in the response (assuming that they are at least `size` composite buckets to return).
  356. If all composite buckets should be retrieved it is preferable to use a small size (`100` or `1000` for instance)
  357. and then use the `after` parameter to retrieve the next results.
  358. For example:
  359. [source,console,id=composite-aggregation-after-key-example]
  360. --------------------------------------------------
  361. GET /_search
  362. {
  363. "size": 0,
  364. "aggs" : {
  365. "my_buckets": {
  366. "composite" : {
  367. "size": 2,
  368. "sources" : [
  369. { "date": { "date_histogram": { "field": "timestamp", "calendar_interval": "1d" } } },
  370. { "product": { "terms": {"field": "product" } } }
  371. ]
  372. }
  373. }
  374. }
  375. }
  376. --------------------------------------------------
  377. // TEST[s/_search/_search\?filter_path=aggregations/]
  378. \... returns:
  379. [source,console-result]
  380. --------------------------------------------------
  381. {
  382. ...
  383. "aggregations": {
  384. "my_buckets": {
  385. "after_key": { <1>
  386. "date": 1494288000000,
  387. "product": "mad max"
  388. },
  389. "buckets": [
  390. {
  391. "key": {
  392. "date": 1494201600000,
  393. "product": "rocky"
  394. },
  395. "doc_count": 1
  396. },
  397. {
  398. "key": {
  399. "date": 1494288000000,
  400. "product": "mad max"
  401. },
  402. "doc_count": 2
  403. }
  404. ]
  405. }
  406. }
  407. }
  408. --------------------------------------------------
  409. // TESTRESPONSE[s/\.\.\.//]
  410. <1> The last composite bucket returned by the query.
  411. NOTE: The `after_key` is equals to the last bucket returned in the response before
  412. any filtering that could be done by <<search-aggregations-pipeline, Pipeline aggregations>>.
  413. If all buckets are filtered/removed by a pipeline aggregation, the `after_key` will contain
  414. the last bucket before filtering.
  415. The `after` parameter can be used to retrieve the composite buckets that are **after**
  416. the last composite buckets returned in a previous round.
  417. For the example below the last bucket can be found in `after_key` and the next
  418. round of result can be retrieved with:
  419. [source,console,id=composite-aggregation-after-example]
  420. --------------------------------------------------
  421. GET /_search
  422. {
  423. "size": 0,
  424. "aggs" : {
  425. "my_buckets": {
  426. "composite" : {
  427. "size": 2,
  428. "sources" : [
  429. { "date": { "date_histogram": { "field": "timestamp", "calendar_interval": "1d", "order": "desc" } } },
  430. { "product": { "terms": {"field": "product", "order": "asc" } } }
  431. ],
  432. "after": { "date": 1494288000000, "product": "mad max" } <1>
  433. }
  434. }
  435. }
  436. }
  437. --------------------------------------------------
  438. <1> Should restrict the aggregation to buckets that sort **after** the provided values.
  439. ==== Early termination
  440. For optimal performance the <<index-modules-index-sorting,index sort>> should be set on the index so that it matches
  441. parts or fully the source order in the composite aggregation.
  442. For instance the following index sort:
  443. [source,console]
  444. --------------------------------------------------
  445. PUT twitter
  446. {
  447. "settings" : {
  448. "index" : {
  449. "sort.field" : ["username", "timestamp"], <1>
  450. "sort.order" : ["asc", "desc"] <2>
  451. }
  452. },
  453. "mappings": {
  454. "properties": {
  455. "username": {
  456. "type": "keyword",
  457. "doc_values": true
  458. },
  459. "timestamp": {
  460. "type": "date"
  461. }
  462. }
  463. }
  464. }
  465. --------------------------------------------------
  466. <1> This index is sorted by `username` first then by `timestamp`.
  467. <2> ... in ascending order for the `username` field and in descending order for the `timestamp` field.
  468. .. could be used to optimize these composite aggregations:
  469. [source,console]
  470. --------------------------------------------------
  471. GET /_search
  472. {
  473. "size": 0,
  474. "aggs" : {
  475. "my_buckets": {
  476. "composite" : {
  477. "sources" : [
  478. { "user_name": { "terms" : { "field": "user_name" } } } <1>
  479. ]
  480. }
  481. }
  482. }
  483. }
  484. --------------------------------------------------
  485. <1> `user_name` is a prefix of the index sort and the order matches (`asc`).
  486. [source,console]
  487. --------------------------------------------------
  488. GET /_search
  489. {
  490. "size": 0,
  491. "aggs" : {
  492. "my_buckets": {
  493. "composite" : {
  494. "sources" : [
  495. { "user_name": { "terms" : { "field": "user_name" } } }, <1>
  496. { "date": { "date_histogram": { "field": "timestamp", "calendar_interval": "1d", "order": "desc" } } } <2>
  497. ]
  498. }
  499. }
  500. }
  501. }
  502. --------------------------------------------------
  503. <1> `user_name` is a prefix of the index sort and the order matches (`asc`).
  504. <2> `timestamp` matches also the prefix and the order matches (`desc`).
  505. In order to optimize the early termination it is advised to set `track_total_hits` in the request
  506. to `false`. The number of total hits that match the request can be retrieved on the first request
  507. and it would be costly to compute this number on every page:
  508. [source,console]
  509. --------------------------------------------------
  510. GET /_search
  511. {
  512. "size": 0,
  513. "track_total_hits": false,
  514. "aggs" : {
  515. "my_buckets": {
  516. "composite" : {
  517. "sources" : [
  518. { "user_name": { "terms" : { "field": "user_name" } } },
  519. { "date": { "date_histogram": { "field": "timestamp", "calendar_interval": "1d", "order": "desc" } } }
  520. ]
  521. }
  522. }
  523. }
  524. }
  525. --------------------------------------------------
  526. Note that the order of the source is important, in the example below switching the `user_name` with the `timestamp`
  527. would deactivate the sort optimization since this configuration wouldn't match the index sort specification.
  528. If the order of sources do not matter for your use case you can follow these simple guidelines:
  529. * Put the fields with the highest cardinality first.
  530. * Make sure that the order of the field matches the order of the index sort.
  531. * Put multi-valued fields last since they cannot be used for early termination.
  532. WARNING: <<index-modules-index-sorting,index sort>> can slowdown indexing, it is very important to test index sorting
  533. with your specific use case and dataset to ensure that it matches your requirement. If it doesn't note that `composite`
  534. aggregations will also try to early terminate on non-sorted indices if the query matches all document (`match_all` query).
  535. ==== Sub-aggregations
  536. Like any `multi-bucket` aggregations the `composite` aggregation can hold sub-aggregations.
  537. These sub-aggregations can be used to compute other buckets or statistics on each composite bucket created by this
  538. parent aggregation.
  539. For instance the following example computes the average value of a field
  540. per composite bucket:
  541. [source,console,id=composite-aggregation-subaggregations-example]
  542. --------------------------------------------------
  543. GET /_search
  544. {
  545. "size": 0,
  546. "aggs" : {
  547. "my_buckets": {
  548. "composite" : {
  549. "sources" : [
  550. { "date": { "date_histogram": { "field": "timestamp", "calendar_interval": "1d", "order": "desc" } } },
  551. { "product": { "terms": {"field": "product" } } }
  552. ]
  553. },
  554. "aggregations": {
  555. "the_avg": {
  556. "avg": { "field": "price" }
  557. }
  558. }
  559. }
  560. }
  561. }
  562. --------------------------------------------------
  563. // TEST[s/_search/_search\?filter_path=aggregations/]
  564. \... returns:
  565. [source,console-result]
  566. --------------------------------------------------
  567. {
  568. ...
  569. "aggregations": {
  570. "my_buckets": {
  571. "after_key": {
  572. "date": 1494201600000,
  573. "product": "rocky"
  574. },
  575. "buckets": [
  576. {
  577. "key": {
  578. "date": 1494460800000,
  579. "product": "apocalypse now"
  580. },
  581. "doc_count": 1,
  582. "the_avg": {
  583. "value": 10.0
  584. }
  585. },
  586. {
  587. "key": {
  588. "date": 1494374400000,
  589. "product": "mad max"
  590. },
  591. "doc_count": 1,
  592. "the_avg": {
  593. "value": 27.0
  594. }
  595. },
  596. {
  597. "key": {
  598. "date": 1494288000000,
  599. "product" : "mad max"
  600. },
  601. "doc_count": 2,
  602. "the_avg": {
  603. "value": 22.5
  604. }
  605. },
  606. {
  607. "key": {
  608. "date": 1494201600000,
  609. "product": "rocky"
  610. },
  611. "doc_count": 1,
  612. "the_avg": {
  613. "value": 10.0
  614. }
  615. }
  616. ]
  617. }
  618. }
  619. }
  620. --------------------------------------------------
  621. // TESTRESPONSE[s/\.\.\.//]
  622. ==== Pipeline aggregations
  623. The composite agg is not currently compatible with pipeline aggregations, nor does it make sense in most cases.
  624. E.g. due to the paging nature of composite aggs, a single logical partition (one day for example) might be spread
  625. over multiple pages. Since pipeline aggregations are purely post-processing on the final list of buckets,
  626. running something like a derivative on a composite page could lead to inaccurate results as it is only taking into
  627. account a "partial" result on that page.
  628. Pipeline aggs that are self contained to a single bucket (such as `bucket_selector`) might be supported in the future.