tophits-aggregation.asciidoc 13 KB

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