# Top hits aggregation performance issue

**URL:** <https://discuss.elastic.co/t/top-hits-aggregation-performance-issue/69840>\
**Category:** Elasticsearch\
**Created:** [December 22, 2016, 7:30pm UTC](https://discuss.elastic.co/t/top-hits-aggregation-performance-issue/69840 "2016-12-22T19:30:48Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![mdcroce](https://avatars.discourse-cdn.com/v4/letter/m/9d8465/32.png) [@mdcroce](https://discuss.elastic.co/u/mdcroce)\
**Post date:** [December 22, 2016, 7:30pm UTC](https://discuss.elastic.co/t/top-hits-aggregation-performance-issue/69840/1 "2016-12-22T19:30:48Z")

</div>

Hi!  
i'm trying to aggregate my query by the field "id\_b2w" and return only the item with the highest score for each bucket ( buckets are ordered by max score). My query is working, but it is slow. Below is the query I'm using, is it the best way to do it?

```
  "aggs": {
    "top_hits": {
      "terms": {
        "field": "id_b2w",
        "size": "20",
        "order": {
          "max_score": "desc"
        }
      },
      "aggs": {
        "by_top_hit": {
          "top_hits": {
            "size": "1"
          }
        },
        "max_score": {
          "max": {
            "lang": "expression",
            "script": "_score"
          }
        }
      }
    }
  }
```

---

<div class="post-metadata">

**Author:** ![system](https://us1.discourse-cdn.com/elastic/original/3X/1/a/1ac57faf039f6b580b3f104ef42a2a89e41014de.png) [@system](https://discuss.elastic.co/u/system)\
**Post date:** [January 19, 2017, 7:30pm UTC](https://discuss.elastic.co/t/top-hits-aggregation-performance-issue/69840/2 "2017-01-19T19:30:50Z")

</div>

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.
