tophits-aggregation.asciidoc 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  1. [[search-aggregations-metrics-top-hits-aggregation]]
  2. === Top Hits Aggregation
  3. A `top_hits` metric aggregator keeps track of the most relevant document being aggregated. This aggregator is intended
  4. to be used as a sub aggregator, so that the top matching documents can be aggregated per bucket.
  5. TIP: We do not recommend using `top_hits` as a top-level aggregation. If you
  6. want to group search hits, use the <<collapse-search-results,`collapse`>>
  7. parameter instead.
  8. The `top_hits` aggregator can effectively be used to group result sets by certain fields via a bucket aggregator.
  9. One or more bucket aggregators determines by which properties a result set get sliced into.
  10. ==== Options
  11. * `from` - The offset from the first result you want to fetch.
  12. * `size` - The maximum number of top matching hits to return per bucket. By default the top three matching hits are returned.
  13. * `sort` - How the top matching hits should be sorted. By default the hits are sorted by the score of the main query.
  14. ==== Supported per hit features
  15. The top_hits aggregation returns regular search hits, because of this many per hit features can be supported:
  16. * <<highlighting,Highlighting>>
  17. * <<request-body-search-explain,Explain>>
  18. * <<named-queries,Named queries>>
  19. * <<source-filtering,Source filtering>>
  20. * <<stored-fields,Stored fields>>
  21. * <<script-fields,Script fields>>
  22. * <<docvalue-fields,Doc value fields>>
  23. * <<request-body-search-version,Include versions>>
  24. * <<request-body-search-seq-no-primary-term,Include Sequence Numbers and Primary Terms>>
  25. IMPORTANT: If you *only* need `docvalue_fields`, `size`, and `sort` then
  26. <<search-aggregations-metrics-top-metrics>> might be a more efficient choice than the Top Hits Aggregation.
  27. `top_hits` does not support the <<rescore,`rescore`>> parameter. Query rescoring
  28. applies only to search hits, not aggregation results. To change the scores used
  29. by aggregations, use a <<query-dsl-function-score-query,`function_score`>> or
  30. <<query-dsl-script-score-query,`script_score`>> query.
  31. ==== Example
  32. In the following example we group the sales by type and per type we show the last sale.
  33. For each sale only the date and price fields are being included in the source.
  34. [source,console]
  35. --------------------------------------------------
  36. POST /sales/_search?size=0
  37. {
  38. "aggs": {
  39. "top_tags": {
  40. "terms": {
  41. "field": "type",
  42. "size": 3
  43. },
  44. "aggs": {
  45. "top_sales_hits": {
  46. "top_hits": {
  47. "sort": [
  48. {
  49. "date": {
  50. "order": "desc"
  51. }
  52. }
  53. ],
  54. "_source": {
  55. "includes": [ "date", "price" ]
  56. },
  57. "size": 1
  58. }
  59. }
  60. }
  61. }
  62. }
  63. }
  64. --------------------------------------------------
  65. // TEST[setup:sales]
  66. Possible response:
  67. [source,console-result]
  68. --------------------------------------------------
  69. {
  70. ...
  71. "aggregations": {
  72. "top_tags": {
  73. "doc_count_error_upper_bound": 0,
  74. "sum_other_doc_count": 0,
  75. "buckets": [
  76. {
  77. "key": "hat",
  78. "doc_count": 3,
  79. "top_sales_hits": {
  80. "hits": {
  81. "total" : {
  82. "value": 3,
  83. "relation": "eq"
  84. },
  85. "max_score": null,
  86. "hits": [
  87. {
  88. "_index": "sales",
  89. "_id": "AVnNBmauCQpcRyxw6ChK",
  90. "_source": {
  91. "date": "2015/03/01 00:00:00",
  92. "price": 200
  93. },
  94. "sort": [
  95. 1425168000000
  96. ],
  97. "_score": null
  98. }
  99. ]
  100. }
  101. }
  102. },
  103. {
  104. "key": "t-shirt",
  105. "doc_count": 3,
  106. "top_sales_hits": {
  107. "hits": {
  108. "total" : {
  109. "value": 3,
  110. "relation": "eq"
  111. },
  112. "max_score": null,
  113. "hits": [
  114. {
  115. "_index": "sales",
  116. "_id": "AVnNBmauCQpcRyxw6ChL",
  117. "_source": {
  118. "date": "2015/03/01 00:00:00",
  119. "price": 175
  120. },
  121. "sort": [
  122. 1425168000000
  123. ],
  124. "_score": null
  125. }
  126. ]
  127. }
  128. }
  129. },
  130. {
  131. "key": "bag",
  132. "doc_count": 1,
  133. "top_sales_hits": {
  134. "hits": {
  135. "total" : {
  136. "value": 1,
  137. "relation": "eq"
  138. },
  139. "max_score": null,
  140. "hits": [
  141. {
  142. "_index": "sales",
  143. "_id": "AVnNBmatCQpcRyxw6ChH",
  144. "_source": {
  145. "date": "2015/01/01 00:00:00",
  146. "price": 150
  147. },
  148. "sort": [
  149. 1420070400000
  150. ],
  151. "_score": null
  152. }
  153. ]
  154. }
  155. }
  156. }
  157. ]
  158. }
  159. }
  160. }
  161. --------------------------------------------------
  162. // TESTRESPONSE[s/\.\.\./"took": $body.took,"timed_out": false,"_shards": $body._shards,"hits": $body.hits,/]
  163. // TESTRESPONSE[s/AVnNBmauCQpcRyxw6ChK/$body.aggregations.top_tags.buckets.0.top_sales_hits.hits.hits.0._id/]
  164. // TESTRESPONSE[s/AVnNBmauCQpcRyxw6ChL/$body.aggregations.top_tags.buckets.1.top_sales_hits.hits.hits.0._id/]
  165. // TESTRESPONSE[s/AVnNBmatCQpcRyxw6ChH/$body.aggregations.top_tags.buckets.2.top_sales_hits.hits.hits.0._id/]
  166. ==== Field collapse example
  167. Field collapsing or result grouping is a feature that logically groups a result set into groups and per group returns
  168. top documents. The ordering of the groups is determined by the relevancy of the first document in a group. In
  169. Elasticsearch this can be implemented via a bucket aggregator that wraps a `top_hits` aggregator as sub-aggregator.
  170. In the example below we search across crawled webpages. For each webpage we store the body and the domain the webpage
  171. belong to. By defining a `terms` aggregator on the `domain` field we group the result set of webpages by domain. The
  172. `top_hits` aggregator is then defined as sub-aggregator, so that the top matching hits are collected per bucket.
  173. Also a `max` aggregator is defined which is used by the `terms` aggregator's order feature to return the buckets by
  174. relevancy order of the most relevant document in a bucket.
  175. [source,console]
  176. --------------------------------------------------
  177. POST /sales/_search
  178. {
  179. "query": {
  180. "match": {
  181. "body": "elections"
  182. }
  183. },
  184. "aggs": {
  185. "top_sites": {
  186. "terms": {
  187. "field": "domain",
  188. "order": {
  189. "top_hit": "desc"
  190. }
  191. },
  192. "aggs": {
  193. "top_tags_hits": {
  194. "top_hits": {}
  195. },
  196. "top_hit" : {
  197. "max": {
  198. "script": {
  199. "source": "_score"
  200. }
  201. }
  202. }
  203. }
  204. }
  205. }
  206. }
  207. --------------------------------------------------
  208. // TEST[setup:sales]
  209. At the moment the `max` (or `min`) aggregator is needed to make sure the buckets from the `terms` aggregator are
  210. ordered according to the score of the most relevant webpage per domain. Unfortunately the `top_hits` aggregator
  211. can't be used in the `order` option of the `terms` aggregator yet.
  212. ==== top_hits support in a nested or reverse_nested aggregator
  213. If the `top_hits` aggregator is wrapped in a `nested` or `reverse_nested` aggregator then nested hits are being returned.
  214. Nested hits are in a sense hidden mini documents that are part of regular document where in the mapping a nested field type
  215. has been configured. The `top_hits` aggregator has the ability to un-hide these documents if it is wrapped in a `nested`
  216. or `reverse_nested` aggregator. Read more about nested in the <<nested,nested type mapping>>.
  217. If nested type has been configured a single document is actually indexed as multiple Lucene documents and they share
  218. the same id. In order to determine the identity of a nested hit there is more needed than just the id, so that is why
  219. nested hits also include their nested identity. The nested identity is kept under the `_nested` field in the search hit
  220. and includes the array field and the offset in the array field the nested hit belongs to. The offset is zero based.
  221. Let's see how it works with a real sample. Considering the following mapping:
  222. [source,console]
  223. --------------------------------------------------
  224. PUT /sales
  225. {
  226. "mappings": {
  227. "properties": {
  228. "tags": { "type": "keyword" },
  229. "comments": { <1>
  230. "type": "nested",
  231. "properties": {
  232. "username": { "type": "keyword" },
  233. "comment": { "type": "text" }
  234. }
  235. }
  236. }
  237. }
  238. }
  239. --------------------------------------------------
  240. <1> The `comments` is an array that holds nested documents under the `product` object.
  241. And some documents:
  242. [source,console]
  243. --------------------------------------------------
  244. PUT /sales/_doc/1?refresh
  245. {
  246. "tags": [ "car", "auto" ],
  247. "comments": [
  248. { "username": "baddriver007", "comment": "This car could have better brakes" },
  249. { "username": "dr_who", "comment": "Where's the autopilot? Can't find it" },
  250. { "username": "ilovemotorbikes", "comment": "This car has two extra wheels" }
  251. ]
  252. }
  253. --------------------------------------------------
  254. // TEST[continued]
  255. It's now possible to execute the following `top_hits` aggregation (wrapped in a `nested` aggregation):
  256. [source,console]
  257. --------------------------------------------------
  258. POST /sales/_search
  259. {
  260. "query": {
  261. "term": { "tags": "car" }
  262. },
  263. "aggs": {
  264. "by_sale": {
  265. "nested": {
  266. "path": "comments"
  267. },
  268. "aggs": {
  269. "by_user": {
  270. "terms": {
  271. "field": "comments.username",
  272. "size": 1
  273. },
  274. "aggs": {
  275. "by_nested": {
  276. "top_hits": {}
  277. }
  278. }
  279. }
  280. }
  281. }
  282. }
  283. }
  284. --------------------------------------------------
  285. // TEST[continued]
  286. // TEST[s/_search/_search\?filter_path=aggregations.by_sale.by_user.buckets/]
  287. Top hits response snippet with a nested hit, which resides in the first slot of array field `comments`:
  288. [source,console-result]
  289. --------------------------------------------------
  290. {
  291. ...
  292. "aggregations": {
  293. "by_sale": {
  294. "by_user": {
  295. "buckets": [
  296. {
  297. "key": "baddriver007",
  298. "doc_count": 1,
  299. "by_nested": {
  300. "hits": {
  301. "total" : {
  302. "value": 1,
  303. "relation": "eq"
  304. },
  305. "max_score": 0.3616575,
  306. "hits": [
  307. {
  308. "_index": "sales",
  309. "_id": "1",
  310. "_nested": {
  311. "field": "comments", <1>
  312. "offset": 0 <2>
  313. },
  314. "_score": 0.3616575,
  315. "_source": {
  316. "comment": "This car could have better brakes", <3>
  317. "username": "baddriver007"
  318. }
  319. }
  320. ]
  321. }
  322. }
  323. }
  324. ...
  325. ]
  326. }
  327. }
  328. }
  329. }
  330. --------------------------------------------------
  331. // TESTRESPONSE[s/\.\.\.//]
  332. <1> Name of the array field containing the nested hit
  333. <2> Position if the nested hit in the containing array
  334. <3> Source of the nested hit
  335. If `_source` is requested then just the part of the source of the nested object is returned, not the entire source of the document.
  336. Also stored fields on the *nested* inner object level are accessible via `top_hits` aggregator residing in a `nested` or `reverse_nested` aggregator.
  337. Only nested hits will have a `_nested` field in the hit, non nested (regular) hits will not have a `_nested` field.
  338. The information in `_nested` can also be used to parse the original source somewhere else if `_source` isn't enabled.
  339. If there are multiple levels of nested object types defined in mappings then the `_nested` information can also be hierarchical
  340. in order to express the identity of nested hits that are two layers deep or more.
  341. In the example below a nested hit resides in the first slot of the field `nested_grand_child_field` which then resides in
  342. the second slow of the `nested_child_field` field:
  343. [source,js]
  344. --------------------------------------------------
  345. ...
  346. "hits": {
  347. "total" : {
  348. "value": 2565,
  349. "relation": "eq"
  350. },
  351. "max_score": 1,
  352. "hits": [
  353. {
  354. "_index": "a",
  355. "_id": "1",
  356. "_score": 1,
  357. "_nested" : {
  358. "field" : "nested_child_field",
  359. "offset" : 1,
  360. "_nested" : {
  361. "field" : "nested_grand_child_field",
  362. "offset" : 0
  363. }
  364. }
  365. "_source": ...
  366. },
  367. ...
  368. ]
  369. }
  370. ...
  371. --------------------------------------------------
  372. // NOTCONSOLE