# Filter documents based aggregation on nested collection

**URL:** <https://discuss.elastic.co/t/filter-documents-based-aggregation-on-nested-collection/107161>\
**Category:** Elasticsearch\
**Created:** [November 10, 2017, 10:07am UTC](https://discuss.elastic.co/t/filter-documents-based-aggregation-on-nested-collection/107161 "2017-11-10T10:07:50Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![hetzer-fastec](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/hetzer-fastec/32/21809_2.png) [@hetzer-fastec](https://discuss.elastic.co/u/hetzer-fastec)\
**Post date:** [November 10, 2017, 10:07am UTC](https://discuss.elastic.co/t/filter-documents-based-aggregation-on-nested-collection/107161/1 "2017-11-10T10:07:50Z")

</div>

Hi everyone,

assume we are modeling restaurants and each restaurant has and id and a nested array of employees. An employee has a name and a salary.

I want to formulate a query which returns all restaurants where the sum of the salaries of the employees exceeds a certain threshold.

I tried experimenting with aggregations only and came up with this:

```
{
  "size": 0,
  "query": {
    "match_all": {
      "boost": 1
    }
  },
  "sort": [],
  "aggs": {
    "test": {
      "terms": {
        "field": "id"
      },
      "aggregations": {
        "nested_employeesSalary": {
          "nested": {
            "path": "employees"
          },
          "aggregations": {
            "employeesSalary": {
              "sum": {
                "field": "employees.salary"
              }
            }
          }
        },
        "sales_bucket_filter": {
          "bucket_selector": {
            "buckets_path": {
              "totalSalaries": "nested_employeesSalary>employeesSalary"
            },
            "script": "params.totalSalaries > 10000"
          }
        }
      }
    }
  }
}

```

This query returns one bucket per restaurant (as I grouped by the restaurant id). The problem is that I am not really interested in the buckets themselved, but in the document (i,e. the restaurant), which is in the bucket.

Now my questions:

1. Is there a way to get the document defining each bucket in the query above?
2. Is there a better way to formulate the query, I want to have?

Thanks in advance!

---

<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:** [December 8, 2017, 10:08am UTC](https://discuss.elastic.co/t/filter-documents-based-aggregation-on-nested-collection/107161/2 "2017-12-08T10:08:29Z")

</div>

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