# Using subaggregations considering only the first x matches

**URL:** <https://discuss.elastic.co/t/using-subaggregations-considering-only-the-first-x-matches/91572>\
**Category:** Elasticsearch\
**Created:** [July 2, 2017, 7:41pm UTC](https://discuss.elastic.co/t/using-subaggregations-considering-only-the-first-x-matches/91572 "2017-07-02T19:41:20Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![DotNet](https://avatars.discourse-cdn.com/v4/letter/d/e47774/32.png) [@DotNet](https://discuss.elastic.co/u/DotNet)\
**Post date:** [July 2, 2017, 7:41pm UTC](https://discuss.elastic.co/t/using-subaggregations-considering-only-the-first-x-matches/91572/1 "2017-07-02T19:41:20Z")

</div>

Hello, I am looking for a subaggregation which considers only the first x matches. I am working on a dataset which consists of thousands of cities, containing amongst others the two fields

- cityName
- cityDescription

The user can search in the field cityDescription to get the most suitable city. Therefore, in the first step, I aggregate the search results by cityName. The second subaggregation is about the score of the found documents. All works fine using the command:

```
GET cityIndex/_search
{
  "query": {
    "match": {
      "cityDescription": "Visit churches and have nice dinner in restaurants and go swimming in the sea"
    }
  } , 
  "aggs": {
    "City": {
      "terms": {
        "field": "cityName",
        "order": {
          "Score.sum": "desc"
        }
      },  
      "aggs": {
        "Score": { 
          "stats": { 
            "script": "_score"
          }
        }
      }
    }
  } 
}

```

In the next step, I only want to consider and include the top ten documents for each city regarding the ranking of the cities.

How can that be done?

Thanks for your answers in advance, kind regards -

DotNet

---

<div class="post-metadata">

**Author:** ![Mark\_Harwood](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/mark_harwood/32/10538_2.png) [@Mark\_Harwood](https://discuss.elastic.co/u/Mark_Harwood)\
**Post date:** [July 3, 2017, 6:54am UTC](https://discuss.elastic.co/t/using-subaggregations-considering-only-the-first-x-matches/91572/2 "2017-07-03T06:54:43Z")

</div>

See the 'sampler' aggregation

---

<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:** [July 31, 2017, 6:54am UTC](https://discuss.elastic.co/t/using-subaggregations-considering-only-the-first-x-matches/91572/3 "2017-07-31T06:54:53Z")

</div>

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