3

Can someone please help me to get an aggregated count of the nested object in elastic search, let say if my elastic search object mapping as :

{
"employe": {
"dynamic": "strict",
"properties": {
  "empId":{
    "type": "keyword"
  },
  "entities": {
     "type": "nested"
      }
   }
 }
}

entities are the type of array with some other object. I wanted to get the count of entities of the filtered item. I have tried some elastic search query, but it does not work

{
"query": {
"bool": {
  "filter": [
    {
      "terms": {
        "empId": [12121,2121212]
      }
    }
  ]
}
},
"size": 0,
"aggs": {
"entities_agg": {
  "sum": {
      "field": "entities",
      "script": {
        "inline": "doc['entities'].values.size()"
      }
    }
  }
 }
}
Ashish Yadav
  • 350
  • 3
  • 17

1 Answers1

10

You cannot access nested data via doc values, you need to access the source document instead, like this:

{
  "query": {
    "bool": {
      "filter": [
        {
          "terms": {
            "empId": [
              12121,
              2121212
            ]
          }
        }
      ]
    }
  },
  "size": 0,
  "aggs": {
    "entities_agg": {
      "sum": {
        "script": {
          "inline": "params._source.entities.size()"
        }
      }
    }
  }
}
Val
  • 207,596
  • 13
  • 358
  • 360
  • I am getting this error { "type": "script_exception", "reason": "runtime error", "script_stack": [ "params._source.entities.size()", " ^---- HERE" ], "script": "params._source.entities.size()", "lang": "painless", "caused_by": { "type": "null_pointer_exception", "reason": null } } – Ashish Yadav Mar 14 '18 at 02:19
  • That's probably because some documents don't have any `entities` field. Is that possible? – Val Mar 14 '18 at 04:01
  • Ok, then which version of ES are you using? – Val Mar 14 '18 at 04:18
  • "version" : { "number" : "5.6.8", "build_date" : "2018-02-16T16:46:30.010Z", "build_snapshot" : false, "lucene_version" : "6.6.1" } – Ashish Yadav Mar 14 '18 at 04:20
  • Can you name a sub-field that is present in all `entities`? – Val Mar 14 '18 at 04:40
  • you are correct, I went through the detail of all the item and one of them I found item don't have entities, Thank you very much your query is working fine for me. – Ashish Yadav Mar 14 '18 at 04:55
  • 1
    Ok, great, glad this helped! – Val Mar 14 '18 at 04:57
  • One more question if my item structure is some thing like this `{ "entities": [ { "sets": [ { "text": "hello", "entityType": "one", "mention": 1 } ] } ] }` then how I can get sets aggregate values now – Ashish Yadav Mar 14 '18 at 04:58
  • this , here i have created https://stackoverflow.com/questions/49270141/how-to-get-array-count-of-nested-of-nested-object-in-elastic-search, if u can help in this also – Ashish Yadav Mar 14 '18 at 05:12