composite-aggregation.asciidoc 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952
  1. [[search-aggregations-bucket-composite-aggregation]]
  2. === Composite aggregation
  3. ++++
  4. <titleabbrev>Composite</titleabbrev>
  5. ++++
  6. WARNING: The composite aggregation is expensive. Load test your application
  7. before deploying a composite aggregation in production.
  8. A multi-bucket aggregation that creates composite buckets from different sources.
  9. Unlike the other `multi-bucket` aggregations, you can use the `composite`
  10. aggregation to paginate **all** buckets from a multi-level aggregation
  11. efficiently. This aggregation provides a way to stream **all** buckets of a
  12. specific aggregation, similar to what
  13. <<scroll-search-results, scroll>> does for documents.
  14. The composite buckets are built from the combinations of the
  15. values extracted/created for each document and each combination is considered as
  16. a composite bucket.
  17. //////////////////////////
  18. [source,console]
  19. --------------------------------------------------
  20. PUT /sales
  21. {
  22. "mappings": {
  23. "properties": {
  24. "product": {
  25. "type": "keyword"
  26. },
  27. "timestamp": {
  28. "type": "date"
  29. },
  30. "price": {
  31. "type": "long"
  32. },
  33. "shop": {
  34. "type": "keyword"
  35. },
  36. "location": {
  37. "type": "geo_point"
  38. },
  39. "nested": {
  40. "type": "nested",
  41. "properties": {
  42. "product": {
  43. "type": "keyword"
  44. },
  45. "timestamp": {
  46. "type": "date"
  47. },
  48. "price": {
  49. "type": "long"
  50. },
  51. "shop": {
  52. "type": "keyword"
  53. }
  54. }
  55. }
  56. }
  57. }
  58. }
  59. POST /sales/_bulk?refresh
  60. {"index":{"_id":0}}
  61. {"product": "mad max", "price": "20", "timestamp": "2017-05-09T14:35"}
  62. {"index":{"_id":1}}
  63. {"product": "mad max", "price": "25", "timestamp": "2017-05-09T12:35"}
  64. {"index":{"_id":2}}
  65. {"product": "rocky", "price": "10", "timestamp": "2017-05-08T09:10"}
  66. {"index":{"_id":3}}
  67. {"product": "mad max", "price": "27", "timestamp": "2017-05-10T07:07"}
  68. {"index":{"_id":4}}
  69. {"product": "apocalypse now", "price": "10", "timestamp": "2017-05-11T08:35"}
  70. -------------------------------------------------
  71. // TESTSETUP
  72. //////////////////////////
  73. For example, consider the following document:
  74. [source,js]
  75. --------------------------------------------------
  76. {
  77. "keyword": ["foo", "bar"],
  78. "number": [23, 65, 76]
  79. }
  80. --------------------------------------------------
  81. // NOTCONSOLE
  82. Using `keyword` and `number` as source fields for the aggregation results in
  83. the following composite buckets:
  84. [source,js]
  85. --------------------------------------------------
  86. { "keyword": "foo", "number": 23 }
  87. { "keyword": "foo", "number": 65 }
  88. { "keyword": "foo", "number": 76 }
  89. { "keyword": "bar", "number": 23 }
  90. { "keyword": "bar", "number": 65 }
  91. { "keyword": "bar", "number": 76 }
  92. --------------------------------------------------
  93. // NOTCONSOLE
  94. ==== Value sources
  95. The `sources` parameter defines the source fields to use when building
  96. composite buckets. The order that the `sources` are defined controls the order
  97. that the keys are returned.
  98. NOTE: You must use a unique name when defining `sources`.
  99. The `sources` parameter can be any of the following types:
  100. * <<_terms,Terms>>
  101. * <<_histogram,Histogram>>
  102. * <<_date_histogram,Date histogram>>
  103. * <<_geotile_grid,GeoTile grid>>
  104. [[_terms]]
  105. ===== Terms
  106. The `terms` value source is similar to a simple `terms` aggregation.
  107. The values are extracted from a field exactly like the `terms` aggregation.
  108. Example:
  109. [source,console,id=composite-aggregation-terms-field-example]
  110. --------------------------------------------------
  111. GET /_search
  112. {
  113. "size": 0,
  114. "aggs": {
  115. "my_buckets": {
  116. "composite": {
  117. "sources": [
  118. { "product": { "terms": { "field": "product" } } }
  119. ]
  120. }
  121. }
  122. }
  123. }
  124. --------------------------------------------------
  125. Like the `terms` aggregation, it's possible to use a
  126. <<runtime,runtime field>> to create values for the composite buckets:
  127. [source,console,id=composite-aggregation-terms-runtime-field-example]
  128. ----
  129. GET /_search
  130. {
  131. "runtime_mappings": {
  132. "day_of_week": {
  133. "type": "keyword",
  134. "script": """
  135. emit(doc['timestamp'].value.dayOfWeekEnum
  136. .getDisplayName(TextStyle.FULL, Locale.ROOT))
  137. """
  138. }
  139. },
  140. "size": 0,
  141. "aggs": {
  142. "my_buckets": {
  143. "composite": {
  144. "sources": [
  145. {
  146. "dow": {
  147. "terms": { "field": "day_of_week" }
  148. }
  149. }
  150. ]
  151. }
  152. }
  153. }
  154. }
  155. ----
  156. ////
  157. [source,console-result]
  158. ----
  159. {
  160. "timed_out": false,
  161. "took": "$body.took",
  162. "_shards": {
  163. "total": 1,
  164. "successful": 1,
  165. "failed": 0,
  166. "skipped": 0
  167. },
  168. "hits": "$body.hits",
  169. "aggregations": {
  170. "my_buckets": {
  171. "after_key": { "dow": "Wednesday" },
  172. "buckets": [
  173. { "key": { "dow": "Monday" }, "doc_count": 1 },
  174. { "key": { "dow": "Thursday" }, "doc_count": 1 },
  175. { "key": { "dow": "Tuesday" }, "doc_count": 2 },
  176. { "key": { "dow": "Wednesday" }, "doc_count": 1 }
  177. ]
  178. }
  179. }
  180. }
  181. ----
  182. ////
  183. Although similar, the `terms` value source doesn't support the same set of
  184. parameters as the `terms` aggregation. For other supported value source
  185. parameters, see:
  186. * <<_order>>
  187. * <<_missing_bucket>>
  188. [[_histogram]]
  189. ===== Histogram
  190. The `histogram` value source can be applied on numeric values to build fixed size
  191. interval over the values. The `interval` parameter defines how the numeric values should be
  192. transformed. For instance an `interval` set to 5 will translate any numeric values to its closest interval,
  193. a value of `101` would be translated to `100` which is the key for the interval between 100 and 105.
  194. Example:
  195. [source,console,id=composite-aggregation-histogram-field-example]
  196. --------------------------------------------------
  197. GET /_search
  198. {
  199. "size": 0,
  200. "aggs": {
  201. "my_buckets": {
  202. "composite": {
  203. "sources": [
  204. { "histo": { "histogram": { "field": "price", "interval": 5 } } }
  205. ]
  206. }
  207. }
  208. }
  209. }
  210. --------------------------------------------------
  211. Like the `histogram` aggregation it's possible to use a
  212. <<runtime,runtime field>> to create values for the composite buckets:
  213. [source,console,id=composite-aggregation-histogram-runtime-field-example]
  214. ----
  215. GET /_search
  216. {
  217. "runtime_mappings": {
  218. "price.discounted": {
  219. "type": "double",
  220. "script": """
  221. double price = doc['price'].value;
  222. if (doc['product'].value == 'mad max') {
  223. price *= 0.8;
  224. }
  225. emit(price);
  226. """
  227. }
  228. },
  229. "size": 0,
  230. "aggs": {
  231. "my_buckets": {
  232. "composite": {
  233. "sources": [
  234. {
  235. "price": {
  236. "histogram": {
  237. "interval": 5,
  238. "field": "price.discounted"
  239. }
  240. }
  241. }
  242. ]
  243. }
  244. }
  245. }
  246. }
  247. ----
  248. ////
  249. [source,console-result]
  250. ----
  251. {
  252. "timed_out": false,
  253. "took": "$body.took",
  254. "_shards": {
  255. "total": 1,
  256. "successful": 1,
  257. "failed": 0,
  258. "skipped": 0
  259. },
  260. "hits": "$body.hits",
  261. "aggregations": {
  262. "my_buckets": {
  263. "after_key": { "price": 20.0 },
  264. "buckets": [
  265. { "key": { "price": 10.0 }, "doc_count": 2 },
  266. { "key": { "price": 15.0 }, "doc_count": 1 },
  267. { "key": { "price": 20.0 }, "doc_count": 2 }
  268. ]
  269. }
  270. }
  271. }
  272. ----
  273. ////
  274. [[_date_histogram]]
  275. ===== Date histogram
  276. The `date_histogram` is similar to the `histogram` value source except that the interval
  277. is specified by date/time expression:
  278. [source,console,id=composite-aggregation-datehistogram-example]
  279. --------------------------------------------------
  280. GET /_search
  281. {
  282. "size": 0,
  283. "aggs": {
  284. "my_buckets": {
  285. "composite": {
  286. "sources": [
  287. { "date": { "date_histogram": { "field": "timestamp", "calendar_interval": "1d" } } }
  288. ]
  289. }
  290. }
  291. }
  292. }
  293. --------------------------------------------------
  294. The example above creates an interval per day and translates all `timestamp` values to the start of its closest intervals.
  295. Available expressions for interval: `year`, `quarter`, `month`, `week`, `day`, `hour`, `minute`, `second`
  296. Time values can also be specified via abbreviations supported by <<time-units,time units>> parsing.
  297. Note that fractional time values are not supported, but you can address this by shifting to another
  298. time unit (e.g., `1.5h` could instead be specified as `90m`).
  299. *Format*
  300. Internally, a date is represented as a 64 bit number representing a timestamp in milliseconds-since-the-epoch.
  301. These timestamps are returned as the bucket keys. It is possible to return a formatted date string instead using
  302. the format specified with the format parameter:
  303. [source,console,id=composite-aggregation-datehistogram-format-example]
  304. --------------------------------------------------
  305. GET /_search
  306. {
  307. "size": 0,
  308. "aggs": {
  309. "my_buckets": {
  310. "composite": {
  311. "sources": [
  312. {
  313. "date": {
  314. "date_histogram": {
  315. "field": "timestamp",
  316. "calendar_interval": "1d",
  317. "format": "yyyy-MM-dd" <1>
  318. }
  319. }
  320. }
  321. ]
  322. }
  323. }
  324. }
  325. }
  326. --------------------------------------------------
  327. <1> Supports expressive date <<date-format-pattern,format pattern>>
  328. *Time Zone*
  329. Date-times are stored in Elasticsearch in UTC. By default, all bucketing and
  330. rounding is also done in UTC. The `time_zone` parameter can be used to indicate
  331. that bucketing should use a different time zone.
  332. Time zones may either be specified as an ISO 8601 UTC offset (e.g. `+01:00` or
  333. `-08:00`) or as a timezone id, an identifier used in the TZ database like
  334. `America/Los_Angeles`.
  335. *Offset*
  336. include::datehistogram-aggregation.asciidoc[tag=offset-explanation]
  337. [source,console,id=composite-aggregation-datehistogram-offset-example]
  338. ----
  339. PUT my-index-000001/_doc/1?refresh
  340. {
  341. "date": "2015-10-01T05:30:00Z"
  342. }
  343. PUT my-index-000001/_doc/2?refresh
  344. {
  345. "date": "2015-10-01T06:30:00Z"
  346. }
  347. GET my-index-000001/_search?size=0
  348. {
  349. "aggs": {
  350. "my_buckets": {
  351. "composite" : {
  352. "sources" : [
  353. {
  354. "date": {
  355. "date_histogram" : {
  356. "field": "date",
  357. "calendar_interval": "day",
  358. "offset": "+6h",
  359. "format": "iso8601"
  360. }
  361. }
  362. }
  363. ]
  364. }
  365. }
  366. }
  367. }
  368. ----
  369. include::datehistogram-aggregation.asciidoc[tag=offset-result-intro]
  370. [source,console-result]
  371. ----
  372. {
  373. ...
  374. "aggregations": {
  375. "my_buckets": {
  376. "after_key": { "date": "2015-10-01T06:00:00.000Z" },
  377. "buckets": [
  378. {
  379. "key": { "date": "2015-09-30T06:00:00.000Z" },
  380. "doc_count": 1
  381. },
  382. {
  383. "key": { "date": "2015-10-01T06:00:00.000Z" },
  384. "doc_count": 1
  385. }
  386. ]
  387. }
  388. }
  389. }
  390. ----
  391. // TESTRESPONSE[s/\.\.\./"took": $body.took,"timed_out": false,"_shards": $body._shards,"hits": $body.hits,/]
  392. include::datehistogram-aggregation.asciidoc[tag=offset-note]
  393. [[_geotile_grid]]
  394. ===== GeoTile grid
  395. The `geotile_grid` value source works on `geo_point` fields and groups points into buckets that represent
  396. cells in a grid. The resulting grid can be sparse and only contains cells
  397. that have matching data. Each cell corresponds to a
  398. {wikipedia}/Tiled_web_map[map tile] as used by many online map
  399. sites. Each cell is labeled using a "{zoom}/{x}/{y}" format, where zoom is equal
  400. to the user-specified precision.
  401. [source,console,id=composite-aggregation-geotilegrid-example]
  402. --------------------------------------------------
  403. GET /_search
  404. {
  405. "size": 0,
  406. "aggs": {
  407. "my_buckets": {
  408. "composite": {
  409. "sources": [
  410. { "tile": { "geotile_grid": { "field": "location", "precision": 8 } } }
  411. ]
  412. }
  413. }
  414. }
  415. }
  416. --------------------------------------------------
  417. *Precision*
  418. The highest-precision geotile of length 29 produces cells that cover
  419. less than 10cm by 10cm of land. This precision is uniquely suited for composite aggregations as each
  420. tile does not have to be generated and loaded in memory.
  421. See https://wiki.openstreetmap.org/wiki/Zoom_levels[Zoom level documentation]
  422. on how precision (zoom) correlates to size on the ground. Precision for this
  423. aggregation can be between 0 and 29, inclusive.
  424. *Bounding box filtering*
  425. The geotile source can optionally be constrained to a specific geo bounding box, which reduces
  426. the range of tiles used. These bounds are useful when only a specific part of a geographical area needs high
  427. precision tiling.
  428. [source,console,id=composite-aggregation-geotilegrid-boundingbox-example]
  429. --------------------------------------------------
  430. GET /_search
  431. {
  432. "size": 0,
  433. "aggs": {
  434. "my_buckets": {
  435. "composite": {
  436. "sources": [
  437. {
  438. "tile": {
  439. "geotile_grid": {
  440. "field": "location",
  441. "precision": 22,
  442. "bounds": {
  443. "top_left": "POINT (4.9 52.4)",
  444. "bottom_right": "POINT (5.0 52.3)"
  445. }
  446. }
  447. }
  448. }
  449. ]
  450. }
  451. }
  452. }
  453. }
  454. --------------------------------------------------
  455. ===== Mixing different value sources
  456. The `sources` parameter accepts an array of value sources.
  457. It is possible to mix different value sources to create composite buckets.
  458. For example:
  459. [source,console,id=composite-aggregation-mixing-sources-example]
  460. --------------------------------------------------
  461. GET /_search
  462. {
  463. "size": 0,
  464. "aggs": {
  465. "my_buckets": {
  466. "composite": {
  467. "sources": [
  468. { "date": { "date_histogram": { "field": "timestamp", "calendar_interval": "1d" } } },
  469. { "product": { "terms": { "field": "product" } } }
  470. ]
  471. }
  472. }
  473. }
  474. }
  475. --------------------------------------------------
  476. This will create composite buckets from the values created by two value sources, a `date_histogram` and a `terms`.
  477. Each bucket is composed of two values, one for each value source defined in the aggregation.
  478. Any type of combinations is allowed and the order in the array is preserved
  479. in the composite buckets.
  480. [source,console,id=composite-aggregation-mixing-three-sources-example]
  481. --------------------------------------------------
  482. GET /_search
  483. {
  484. "size": 0,
  485. "aggs": {
  486. "my_buckets": {
  487. "composite": {
  488. "sources": [
  489. { "shop": { "terms": { "field": "shop" } } },
  490. { "product": { "terms": { "field": "product" } } },
  491. { "date": { "date_histogram": { "field": "timestamp", "calendar_interval": "1d" } } }
  492. ]
  493. }
  494. }
  495. }
  496. }
  497. --------------------------------------------------
  498. [[_order]]
  499. ==== Order
  500. By default the composite buckets are sorted by their natural ordering. Values are sorted
  501. in ascending order of their values. When multiple value sources are requested, the ordering is done per value
  502. 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
  503. next values in the composite bucket are used for tie-breaking. This means that the composite bucket
  504. `[foo, 100]` is considered smaller than `[foobar, 0]` because `foo` is considered smaller than `foobar`.
  505. It is possible to define the direction of the sort for each value source by setting `order` to `asc` (default value)
  506. or `desc` (descending order) directly in the value source definition.
  507. For example:
  508. [source,console,id=composite-aggregation-order-example]
  509. --------------------------------------------------
  510. GET /_search
  511. {
  512. "size": 0,
  513. "aggs": {
  514. "my_buckets": {
  515. "composite": {
  516. "sources": [
  517. { "date": { "date_histogram": { "field": "timestamp", "calendar_interval": "1d", "order": "desc" } } },
  518. { "product": { "terms": { "field": "product", "order": "asc" } } }
  519. ]
  520. }
  521. }
  522. }
  523. }
  524. --------------------------------------------------
  525. \... will sort the composite bucket in descending order when comparing values from the `date_histogram` source
  526. and in ascending order when comparing values from the `terms` source.
  527. [[_missing_bucket]]
  528. ==== Missing bucket
  529. By default documents without a value for a given source are ignored.
  530. It is possible to include them in the response by setting `missing_bucket` to
  531. `true` (defaults to `false`):
  532. [source,console,id=composite-aggregation-missing-bucket-example]
  533. --------------------------------------------------
  534. GET /_search
  535. {
  536. "size": 0,
  537. "aggs": {
  538. "my_buckets": {
  539. "composite": {
  540. "sources": [{
  541. "product_name": {
  542. "terms": {
  543. "field": "product",
  544. "missing_bucket": true,
  545. "missing_order": "last"
  546. }
  547. }
  548. }]
  549. }
  550. }
  551. }
  552. }
  553. --------------------------------------------------
  554. In the above example, the `product_name` source emits an explicit `null` bucket
  555. for documents without a `product` value. This bucket is placed last.
  556. You can control the position of the `null` bucket using the optional
  557. `missing_order` parameter. If `missing_order` is `first` or `last`, the `null`
  558. bucket is placed in the respective first or last position. If `missing_order` is
  559. omitted or `default`, the source's `order` determines the bucket's position. If
  560. `order` is `asc` (ascending), the bucket is in the first position. If `order` is
  561. `desc` (descending), the bucket is in the last position.
  562. ==== Size
  563. The `size` parameter can be set to define how many composite buckets should be returned.
  564. Each composite bucket is considered as a single bucket, so setting a size of 10 will return the
  565. first 10 composite buckets created from the value sources.
  566. The response contains the values for each composite bucket in an array containing the values extracted
  567. from each value source. Defaults to `10`.
  568. ==== Pagination
  569. If the number of composite buckets is too high (or unknown) to be returned in a single response
  570. it is possible to split the retrieval in multiple requests.
  571. Since the composite buckets are flat by nature, the requested `size` is exactly the number of composite buckets
  572. that will be returned in the response (assuming that they are at least `size` composite buckets to return).
  573. If all composite buckets should be retrieved it is preferable to use a small size (`100` or `1000` for instance)
  574. and then use the `after` parameter to retrieve the next results.
  575. For example:
  576. [source,console,id=composite-aggregation-after-key-example]
  577. --------------------------------------------------
  578. GET /_search
  579. {
  580. "size": 0,
  581. "aggs": {
  582. "my_buckets": {
  583. "composite": {
  584. "size": 2,
  585. "sources": [
  586. { "date": { "date_histogram": { "field": "timestamp", "calendar_interval": "1d" } } },
  587. { "product": { "terms": { "field": "product" } } }
  588. ]
  589. }
  590. }
  591. }
  592. }
  593. --------------------------------------------------
  594. // TEST[s/_search/_search\?filter_path=aggregations/]
  595. \... returns:
  596. [source,console-result]
  597. --------------------------------------------------
  598. {
  599. ...
  600. "aggregations": {
  601. "my_buckets": {
  602. "after_key": {
  603. "date": 1494288000000,
  604. "product": "mad max"
  605. },
  606. "buckets": [
  607. {
  608. "key": {
  609. "date": 1494201600000,
  610. "product": "rocky"
  611. },
  612. "doc_count": 1
  613. },
  614. {
  615. "key": {
  616. "date": 1494288000000,
  617. "product": "mad max"
  618. },
  619. "doc_count": 2
  620. }
  621. ]
  622. }
  623. }
  624. }
  625. --------------------------------------------------
  626. // TESTRESPONSE[s/\.\.\.//]
  627. To get the next set of buckets, resend the same aggregation with the `after`
  628. parameter set to the `after_key` value returned in the response.
  629. For example, this request uses the `after_key` value provided in the previous response:
  630. [source,console,id=composite-aggregation-after-example]
  631. --------------------------------------------------
  632. GET /_search
  633. {
  634. "size": 0,
  635. "aggs": {
  636. "my_buckets": {
  637. "composite": {
  638. "size": 2,
  639. "sources": [
  640. { "date": { "date_histogram": { "field": "timestamp", "calendar_interval": "1d", "order": "desc" } } },
  641. { "product": { "terms": { "field": "product", "order": "asc" } } }
  642. ],
  643. "after": { "date": 1494288000000, "product": "mad max" } <1>
  644. }
  645. }
  646. }
  647. }
  648. --------------------------------------------------
  649. <1> Should restrict the aggregation to buckets that sort **after** the provided values.
  650. NOTE: The `after_key` is *usually* the key to the last bucket returned in
  651. the response, but that isn't guaranteed. Always use the returned `after_key` instead
  652. of derriving it from the buckets.
  653. ==== Early termination
  654. For optimal performance the <<index-modules-index-sorting,index sort>> should be set on the index so that it matches
  655. parts or fully the source order in the composite aggregation.
  656. For instance the following index sort:
  657. [source,console]
  658. --------------------------------------------------
  659. PUT my-index-000001
  660. {
  661. "settings": {
  662. "index": {
  663. "sort.field": [ "username", "timestamp" ], <1>
  664. "sort.order": [ "asc", "desc" ] <2>
  665. }
  666. },
  667. "mappings": {
  668. "properties": {
  669. "username": {
  670. "type": "keyword",
  671. "doc_values": true
  672. },
  673. "timestamp": {
  674. "type": "date"
  675. }
  676. }
  677. }
  678. }
  679. --------------------------------------------------
  680. <1> This index is sorted by `username` first then by `timestamp`.
  681. <2> ... in ascending order for the `username` field and in descending order for the `timestamp` field.
  682. .. could be used to optimize these composite aggregations:
  683. [source,console]
  684. --------------------------------------------------
  685. GET /_search
  686. {
  687. "size": 0,
  688. "aggs": {
  689. "my_buckets": {
  690. "composite": {
  691. "sources": [
  692. { "user_name": { "terms": { "field": "user_name" } } } <1>
  693. ]
  694. }
  695. }
  696. }
  697. }
  698. --------------------------------------------------
  699. <1> `user_name` is a prefix of the index sort and the order matches (`asc`).
  700. [source,console]
  701. --------------------------------------------------
  702. GET /_search
  703. {
  704. "size": 0,
  705. "aggs": {
  706. "my_buckets": {
  707. "composite": {
  708. "sources": [
  709. { "user_name": { "terms": { "field": "user_name" } } }, <1>
  710. { "date": { "date_histogram": { "field": "timestamp", "calendar_interval": "1d", "order": "desc" } } } <2>
  711. ]
  712. }
  713. }
  714. }
  715. }
  716. --------------------------------------------------
  717. <1> `user_name` is a prefix of the index sort and the order matches (`asc`).
  718. <2> `timestamp` matches also the prefix and the order matches (`desc`).
  719. In order to optimize the early termination it is advised to set `track_total_hits` in the request
  720. to `false`. The number of total hits that match the request can be retrieved on the first request
  721. and it would be costly to compute this number on every page:
  722. [source,console]
  723. --------------------------------------------------
  724. GET /_search
  725. {
  726. "size": 0,
  727. "track_total_hits": false,
  728. "aggs": {
  729. "my_buckets": {
  730. "composite": {
  731. "sources": [
  732. { "user_name": { "terms": { "field": "user_name" } } },
  733. { "date": { "date_histogram": { "field": "timestamp", "calendar_interval": "1d", "order": "desc" } } }
  734. ]
  735. }
  736. }
  737. }
  738. }
  739. --------------------------------------------------
  740. Note that the order of the source is important, in the example below switching the `user_name` with the `timestamp`
  741. would deactivate the sort optimization since this configuration wouldn't match the index sort specification.
  742. If the order of sources do not matter for your use case you can follow these simple guidelines:
  743. * Put the fields with the highest cardinality first.
  744. * Make sure that the order of the field matches the order of the index sort.
  745. * Put multi-valued fields last since they cannot be used for early termination.
  746. WARNING: <<index-modules-index-sorting,index sort>> can slowdown indexing, it is very important to test index sorting
  747. with your specific use case and dataset to ensure that it matches your requirement. If it doesn't note that `composite`
  748. aggregations will also try to early terminate on non-sorted indices if the query matches all document (`match_all` query).
  749. ==== Sub-aggregations
  750. Like any `multi-bucket` aggregations the `composite` aggregation can hold sub-aggregations.
  751. These sub-aggregations can be used to compute other buckets or statistics on each composite bucket created by this
  752. parent aggregation.
  753. For instance the following example computes the average value of a field
  754. per composite bucket:
  755. [source,console,id=composite-aggregation-subaggregations-example]
  756. --------------------------------------------------
  757. GET /_search
  758. {
  759. "size": 0,
  760. "aggs": {
  761. "my_buckets": {
  762. "composite": {
  763. "sources": [
  764. { "date": { "date_histogram": { "field": "timestamp", "calendar_interval": "1d", "order": "desc" } } },
  765. { "product": { "terms": { "field": "product" } } }
  766. ]
  767. },
  768. "aggregations": {
  769. "the_avg": {
  770. "avg": { "field": "price" }
  771. }
  772. }
  773. }
  774. }
  775. }
  776. --------------------------------------------------
  777. // TEST[s/_search/_search\?filter_path=aggregations/]
  778. \... returns:
  779. [source,console-result]
  780. --------------------------------------------------
  781. {
  782. ...
  783. "aggregations": {
  784. "my_buckets": {
  785. "after_key": {
  786. "date": 1494201600000,
  787. "product": "rocky"
  788. },
  789. "buckets": [
  790. {
  791. "key": {
  792. "date": 1494460800000,
  793. "product": "apocalypse now"
  794. },
  795. "doc_count": 1,
  796. "the_avg": {
  797. "value": 10.0
  798. }
  799. },
  800. {
  801. "key": {
  802. "date": 1494374400000,
  803. "product": "mad max"
  804. },
  805. "doc_count": 1,
  806. "the_avg": {
  807. "value": 27.0
  808. }
  809. },
  810. {
  811. "key": {
  812. "date": 1494288000000,
  813. "product": "mad max"
  814. },
  815. "doc_count": 2,
  816. "the_avg": {
  817. "value": 22.5
  818. }
  819. },
  820. {
  821. "key": {
  822. "date": 1494201600000,
  823. "product": "rocky"
  824. },
  825. "doc_count": 1,
  826. "the_avg": {
  827. "value": 10.0
  828. }
  829. }
  830. ]
  831. }
  832. }
  833. }
  834. --------------------------------------------------
  835. // TESTRESPONSE[s/\.\.\.//]
  836. [[search-aggregations-bucket-composite-aggregation-pipeline-aggregations]]
  837. ==== Pipeline aggregations
  838. The composite agg is not currently compatible with pipeline aggregations, nor does it make sense in most cases.
  839. E.g. due to the paging nature of composite aggs, a single logical partition (one day for example) might be spread
  840. over multiple pages. Since pipeline aggregations are purely post-processing on the final list of buckets,
  841. running something like a derivative on a composite page could lead to inaccurate results as it is only taking into
  842. account a "partial" result on that page.
  843. Pipeline aggs that are self contained to a single bucket (such as `bucket_selector`) might be supported in the future.