# Get the latest document version and aggregate the results

**URL:** <https://discuss.elastic.co/t/get-the-latest-document-version-and-aggregate-the-results/61384>\
**Category:** Elasticsearch\
**Created:** [September 23, 2016, 12:53pm UTC](https://discuss.elastic.co/t/get-the-latest-document-version-and-aggregate-the-results/61384 "2016-09-23T12:53:17Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Taras\_Kohut](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/taras_kohut/32/12118_2.png) [@Taras\_Kohut](https://discuss.elastic.co/u/Taras_Kohut)\
**Post date:** [September 23, 2016, 12:53pm UTC](https://discuss.elastic.co/t/get-the-latest-document-version-and-aggregate-the-results/61384/1 "2016-09-23T12:53:17Z")

</div>

My index contains a lot of documents, each of them has several versions, for example:

```
{"doc_id": 13,
"version": 1,
"text": "bar"}

{"doc_id": 13,
"version": 2,
"text": "bar"}

{"doc_id": 13,
"version": 3,
"text": "bar"}

{"doc_id": 14,
"version": 1,
"text": "foo"}

{"doc_id": 14,
"version": 2,
"text": "bar"}

```

I want to get the last version for each document, and aggregate them (last versions) using `terms` aggregation.  
I've tried to use `top hits` to retrieve last versions:

```
{"size" :0,
"aggs" : {
    "doc_id_groups" : {
        "terms" : {
            "field" : "doc_id",
            "size" : "0"
        },
        "aggs" : {
            "docs" : {
                "top_hits" : {
                    "size" : 1,
                    "sort" : {
                        "version" : {
                            "order" : "desc"
                        }
                    }
                },
                "aggs" : {
                  "text_agg" : {
                    "terms" : { "field" : "text" }
                            }
                       }
                  }
        }
    }
}
}

```

But I can't use `text_agg` aggregation, because `top hits` doesn't support sub aggregations.  
I'm expecting this response: `"buckets": [{ "key": "bar", "doc_count": 2 }]`  
I guess retrieving ids and then aggregating them would be very heavy operation for the client.  
Maybe scripting could help?  
Update: I found a very non-flexible workaround. See here: [http://stackoverflow.com/a/39788948/4769188](http://stackoverflow.com/a/39788948/4769188)  
But I'm still looking for better solution.

---

<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 5, 2017, 10:12pm UTC](https://discuss.elastic.co/t/get-the-latest-document-version-and-aggregate-the-results/61384/2 "2017-07-05T22:12:37Z")

</div>


