# Elasticsearch query to filter count by aggregate

**URL:** <https://discuss.elastic.co/t/elasticsearch-query-to-filter-count-by-aggregate/147077>\
**Category:** Elasticsearch\
**Created:** [September 3, 2018, 12:39pm UTC](https://discuss.elastic.co/t/elasticsearch-query-to-filter-count-by-aggregate/147077 "2018-09-03T12:39:33Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Ambuj\_Jauhari](https://avatars.discourse-cdn.com/v4/letter/a/82dd89/32.png) [@Ambuj\_Jauhari](https://discuss.elastic.co/u/Ambuj_Jauhari)\
**Post date:** [September 3, 2018, 12:39pm UTC](https://discuss.elastic.co/t/elasticsearch-query-to-filter-count-by-aggregate/147077/1 "2018-09-03T12:39:33Z")

</div>

I am writing a query to count documents, group by modifiedDateTime. This query works fine as below

```
{
    "aggs" : {
        "types_count" : { 
          "value_count" : { "field" : "id" }
        },
        "group_by_status": {
          "terms": {
            "field": "status.keyword"
          }
        }
    }
}

```

This query gives me the proper buckets as below

```
"buckets": [
        {
          "key": "STARTED",
          "doc_count": 579873
        },
        {
          "key": "SENT",
          "doc_count": 363026
        },

```

Now our process is such that once its triggered its state is STARTED, next its SEND, then its AWATING\_RESPONSE, then it goes to COMPLETED and each time process moves to next state its version is incremented.

So essentially with above query i am counting all the process which are in different state, but the trick here is a process which is STARTED is also counted in SENT since its the same process with different version.

Now how i want to create a query is to provide me the count for all the different stated but it should consider only the latest version not all versions.

I tried something like below

```
{
    "aggs" : {
        "types_count" : { 
          "value_count" : { "field" : "id" }
        },
        "aggs" : {
          "max_version" : { "max" : { "field" : "version" } }
        },
        "group_by_status": {
          "terms": {
            "field": "status.keyword"
          }
        }
    }
}

```

but it gives me this error

```
"root_cause": [
      {
        "type": "named_object_not_found_exception",
        "reason": "[7:27] unable to parse BaseAggregationBuilder with name [max_version]: parser not found"
      }
    ]

```

Any way this can be achieved ?

---

<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:** [October 1, 2018, 12:39pm UTC](https://discuss.elastic.co/t/elasticsearch-query-to-filter-count-by-aggregate/147077/2 "2018-10-01T12:39:33Z")

</div>

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