0

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?

JVK
  • 3,782
  • 8
  • 43
  • 67

1 Answers1

0

This is how you can get value of nested objects:

PUT intstitutes
{
  "mappings": {
    "log": {
      "properties": {
        "schools": {
          "type": "object",
          "dynamic": true,
          "properties": {}
        }
      }
    }
  }
}

PUT /intstitutes/log/1?refresh
{
  "schools": {
    "3546": {
      "max": 12,
      "min": 10
    },
    "3896": {
      "max": 18,
      "min": 12
    },
    "8291": {
      "max": 11,
      "min": 11
    }
  }
}

POST intstitutes/_search
{
  "query": {
    "match": {
      "_id": "1"
    }
  },
  "script_fields": {
    "script_score": {
      "script": {
        "params": {
          "key": "3896"
        },
        "source": "if (params._source.containsKey('schools') && params._source.schools.containsKey(params.key)) { return params._source.schools.get(params.key).min } else { return 0 }"
      }
    }
  }
}
DELETE intstitutes
Rahul Singhai
  • 1,299
  • 15
  • 27