# Terms aggregation not working for nested fields

**URL:** <https://discuss.elastic.co/t/terms-aggregation-not-working-for-nested-fields/62799>\
**Category:** Elasticsearch\
**Created:** [October 12, 2016, 11:05am UTC](https://discuss.elastic.co/t/terms-aggregation-not-working-for-nested-fields/62799 "2016-10-12T11:05:49Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![sruthi](https://avatars.discourse-cdn.com/v4/letter/s/ee7513/32.png) [@sruthi](https://discuss.elastic.co/u/sruthi)\
**Post date:** [October 12, 2016, 11:05am UTC](https://discuss.elastic.co/t/terms-aggregation-not-working-for-nested-fields/62799/1 "2016-10-12T11:05:49Z")

</div>

I have created an index with the mapping like

```auto
  "mappings": {
  "event":{
      "properties": {
        "payload":{
        "type":"nested",
        "properties":{
        "serviceName": {
          "type": "string",
          "index": "not_analyzed"
        }....}

```

I am trying the below query. It returns null buckets always. If I am changing the field to be analyzed, it works but service name is split.

```auto
{
  "size" : 0,
  "aggs" : {
    "services" : {
        "terms" : {
            "field" : "payload.serviceName" 
        }
    }
  }
}

```

How to fix this?

---

<div class="post-metadata">

**Author:** ![jpountz](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/jpountz/32/45836_2.png) [@jpountz](https://discuss.elastic.co/u/jpountz)\
**Post date:** [October 14, 2016, 2:29pm UTC](https://discuss.elastic.co/t/terms-aggregation-not-working-for-nested-fields/62799/2 "2016-10-14T14:29:19Z")

</div>

Since your mappings have a nested field, you need to use the `nested` aggregation.

```auto
{
  "size" : 0,
  "aggs" : {
   "payloads": {
      "nested": {
        "path": "payloads"
      },
      "aggs": {
        "services" : {
          "terms" : {
            "field" : "payload.serviceName" 
          }
        }
      }
    }
  }
}

```

---

<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/terms-aggregation-not-working-for-nested-fields/62799/3 "2017-07-05T22:12:16Z")

</div>


