# Unable to get terms + terms + top hits aggregation

**URL:** <https://discuss.elastic.co/t/unable-to-get-terms-terms-top-hits-aggregation/233650>\
**Category:** Elasticsearch\
**Created:** [May 21, 2020, 2:45am UTC](https://discuss.elastic.co/t/unable-to-get-terms-terms-top-hits-aggregation/233650 "2020-05-21T02:45:18Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Andy93](https://avatars.discourse-cdn.com/v4/letter/a/a4c791/32.png) [@Andy93](https://discuss.elastic.co/u/Andy93)\
**Post date:** [May 21, 2020, 2:45am UTC](https://discuss.elastic.co/t/unable-to-get-terms-terms-top-hits-aggregation/233650/1 "2020-05-21T02:45:18Z")

</div>

Hi, I am trying to do a terms + terms + top hits aggregation on an index of ~5.4m documents.  
The relevant fields are equipment ID, location, and the timestamp.

I want to get the latest location of the equipment via the latest timestamp, and use only that latest location to aggregate into location buckets with the count of equipment in that location.

Here's what I have so far:

```auto
    {
     "track_total_hits": True,
     "size": 0,
     "aggs" : {
      "pol": {
       "terms": {
        "field": "nest.eventLoc.keyword",
        "size": loc_count
       },
       "aggs": {
        "eqpmt": {
         "terms": {
          "field": "nest.eqpmtId.keyword",
          "size": eqpmt_count,
         },
         "aggs": {
          "latest": {
           "top_hits": {
            "sort": [
            	{ "nest.actualDateTime": { "order": "desc" } }
            	],
            	"size": 1,
                "_source" : False
           }
          }
         }
        }
       }
      }
     }
    }

```

The end result is returning count of all documents by location (i.e., duplicate equipment IDs), and not the count of unique documents by their latest location. Am I missing some keyword somewhere?

I am on 7.6.1.  
Thanks.

---

<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:** [June 18, 2020, 2:45am UTC](https://discuss.elastic.co/t/unable-to-get-terms-terms-top-hits-aggregation/233650/2 "2020-06-18T02:45:20Z")

</div>

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