Terms aggregation not working for nested fields

I have created an index with the mapping like

  "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.

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

How to fix this?

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

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