# Count the result of an aggregation

**URL:** <https://discuss.elastic.co/t/count-the-result-of-an-aggregation/51429>\
**Category:** Elasticsearch\
**Created:** [May 31, 2016, 12:53pm UTC](https://discuss.elastic.co/t/count-the-result-of-an-aggregation/51429 "2016-05-31T12:53:59Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![jupp](https://avatars.discourse-cdn.com/v4/letter/j/e36b37/32.png) [@jupp](https://discuss.elastic.co/u/jupp)\
**Post date:** [May 31, 2016, 12:53pm UTC](https://discuss.elastic.co/t/count-the-result-of-an-aggregation/51429/1 "2016-05-31T12:53:59Z")

</div>

Given then following Dataset:

```
id @timestamp message
1 2016-05-03T16:30:39.000Z online
2 2016-05-03T16:29:39.000Z online
1 2016-05-03T15:30:39.000Z dead
3 2016-05-03T15:27:39.000Z online
4 2016-05-03T15:28:39.000Z dead
3 2016-05-03T15:25:39.000Z dead
2 2016-05-03T14:29:39.000Z dead
4 2016-05-03T14:28:39.000Z online

```

I want to get the last Event per id and the Count how many ids are "online" or "dead"

The result should be:

```
{
 "key": "online"
 "doc_count": 3
},
{
 "key": "dead"
 "doc_count": 1
}

```

I tried following:

```
{
  "size": 0,
  "aggs": {
    "all_ids": {
      "terms": {
        "field": "id",
        "size": 4
      },
      "aggs": {
        "last_event": {
          "top_hits": {
            "sort": [
              {
                "@timestamp": {
                  "order": "desc"
                }
              }
            ],
            "_source": {
              "include": [
                "message",
                "@timestamp"
              ]
            },
            "size": 1
          }
        }
      }
    }
  }
}

```

But this gives me only 4 Buckets, in each the last Event.

---

<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:47pm UTC](https://discuss.elastic.co/t/count-the-result-of-an-aggregation/51429/2 "2017-07-05T22:47:39Z")

</div>


