# Elasticsearch aggregation over full index but over query results is needed

**URL:** <https://discuss.elastic.co/t/elasticsearch-aggregation-over-full-index-but-over-query-results-is-needed/230392>\
**Category:** Elasticsearch\
**Created:** [April 29, 2020, 2:31pm UTC](https://discuss.elastic.co/t/elasticsearch-aggregation-over-full-index-but-over-query-results-is-needed/230392 "2020-04-29T14:31:27Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![kengreenlee](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/kengreenlee/32/67376_2.png) [@kengreenlee](https://discuss.elastic.co/u/kengreenlee)\
**Post date:** [April 29, 2020, 2:31pm UTC](https://discuss.elastic.co/t/elasticsearch-aggregation-over-full-index-but-over-query-results-is-needed/230392/1 "2020-04-29T14:31:27Z")

</div>

I have what I think should be a simple query. I'm trying to return the documents in descending order by amount and ascending by name (actually, it's name.keyword). For the cases with duplicate names, I only want one name (so it's an aggregation). The problem is that Elasticsearch is ignoring the query results when applying the aggregation. It's as if the aggregation is over the entire data and not the query results. Here's my query:

```auto
    {
        "from": 0,
        "size": 5,
        "sort": [
            {
                "amount": "desc",
                "name.keyword": "asc"
            }
        ],
        "query": {
            "bool": {
                "must": [
                    {
                        "exists": {
                            "field": "name"
                        }
                    },
                    {
                        "exists": {
                            "field": "amount"
                        }
                    }
                ]
            }
        },
        "aggs": {
            "buckets": {
                "composite": {
                    "size": 5,
                    "sources": [
                        {
                            "name": {
                                "terms": {
                                    "field": "name.keyword",
                                    "order": "asc"
                                }
                            }
                        }
                    ]
                }
            }
        }
    }

```

Any idea how to do the aggregation over the query requests only and not the full index?

---

<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:** [May 27, 2020, 2:31pm UTC](https://discuss.elastic.co/t/elasticsearch-aggregation-over-full-index-but-over-query-results-is-needed/230392/2 "2020-05-27T14:31:32Z")

</div>

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