tophits-aggregation.asciidoc 13 KB

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