Accessing the value of a dynamic key in an object

Partial mapping of one of my index is as follows:

"schools": {
  "type": "object",
  "dynamic": true,
  "properties": {}
}

A sample schools object of an existing document is:

"schools": {
  "8291": {
    "max": 11,
    "min": 11
  },
  "3546": {
    "max": 12,
    "min": 10
  },
  "3896": {
    "max": 18,
    "min": 12
  }
}

I have painless script in ES6.2 where dynamically key (e.g. 3896) is computed on runtime and passed to script as a parameter

"script": {
  "params": {
    "key": key
  },
  "source": {
    if (doc.containsKey('schools') && doc.schools.containsKey(key)){
      String dynamic_key = "schools."+key+".min";
      return doc[dynamic_key].value;
    } else {
      return 0;
  }
}

So if passed key value is 3896, then this should return 12. But I get an error message

No field found for [schools.3896.min] in mapping with types [myindexname]

What am I doing wrong? What is the correct way to access a dynamic object where a key name is computed on runtime to fetch its value?

How many different values under "schools" are you going to have in your index?

@Igor_Motov at a particular time it would be 72, but these kay names changes every week.

Do you have a daily or weekly indices? If not, increasing the number of dynamic fields is not going to be as sustainable solution.

No, I don't have weekly/daily indices.

In this case I would try to avoid having dynamic fields here. What kind of searches are you planning to do with data and what are you trying to achieve by using the script?

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