How to access objects fields nested value in runtime field painless (or expression) scripts?

I have a document like this:

POST test/_doc
{
  "name":"Ali",
  "age":20,
  "grades":[
    {
    "title":"math",
    "score":1
    },
    {
    "title":"english",
    "score":2
    },
    {
    "title":"physic",
    "score":3
    }
  ]
}

and I want to have a runtime field with avg of each doc grade scores. then use that run time field in my queries. but I cant access to score in grades objects and there is nothing about accessing objects fields in scripting documentations.

i try these but all produce errors and none of them works:

doc['grades'][0]['score'].value
doc['grades.0.score'].value
doc['grades'].0.score
doc['grades'][0].score
field('grades.0.score').get(null)
for(i in field('grades').get([])){
  sum +=  i.score;
 sum += i['score']; // or this
}

Hey,

how about this?

POST test/_doc/1
{
  "name":"Ali",
  "age":20,
  "grades":[
    {
    "title":"math",
    "score":1
    },
    {
    "title":"english",
    "score":2
    },
    {
    "title":"physic",
    "score":3
    }
  ]
}

GET test/_mapping

GET test/_search
{
  "runtime_mappings": {
    "average": {
      "type": "double",
      "script": {
        "source": """
        emit(doc['grades.score'].sum()/doc['grades.score'].size());
        """ 
      }
    }
  },
  "aggs": {
    "average": {
      "stats": {
        "field": "average"
      }
    }
  }
}
1 Like

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.