banerjeesouvik
banerjeesouvik

Reputation: 212

Elasticsearch Aggregation on array of single objects

My query search result is of following structure

[   
     {
        "_index" : "xxxx",
        "_type" : "status",
        "_id" : "01xxxxxxxxxxx",
        "_score" : 6.297049,
        "_source" : {
          "messageDetail" : {
            "errors" : [
              {
                "errorMessage" : ".metaData should have required property 'schemaVersion'"
              }
            ]
          }
        }
      },
      {
        "_index" : "xxxx",
        "_type" : "status",
        "_id" : "076XXXXxxx",
        "_score" : 6.297049,
        "_source" : {
          "messageDetail" : {
            "errors" : [
              {
                "errorMessage" : ".metaData should have required property 'scenarioName'"
              }
            ]
          }
        }
      },
...]

I would like to aggregate over messageDetail.errors.errorMessage and create a map alike structure that will hold the different error messages and their number of occurrence in a key-value pair.

P.S. - messageDetail.error is an array of single object.

Can someone please provide any query for the same.

Upvotes: 1

Views: 160

Answers (1)

Bhavya
Bhavya

Reputation: 16172

Adding a working example with index data (used same as that given in question), index mapping, search query, and search result

Index Mapping:

{
  "mappings": {
    "properties": {
      "messageDetail": {
        "properties": {
          "errors": {
            "properties": {
              "errorMessage": {
                "type": "keyword"
              }
            }
          }
        }
      }
    }
  }
}

Search Query

{
    "size": 0, 
    "aggs" : {
        "states" : {
            "terms" : { 
                "field" : "messageDetail.errors.errorMessage"
            }
        }
    }
}

Search Result:

"aggregations": {
    "states": {
      "doc_count_error_upper_bound": 0,
      "sum_other_doc_count": 0,
      "buckets": [
        {
          "key": ".metaData should have required property 'scenarioName'",
          "doc_count": 1
        },
        {
          "key": ".metaData should have required property 'schemaVersion'",
          "doc_count": 1
        }
      ]
    }

Upvotes: 1

Related Questions