Reputation: 2961
I'm trying to make a select query with a Painless script, but I keep getting an error in the response that the script is not valid.
What I'm trying to do in this simplified script is to check if my given param ages are both adult following the age in 'unit.info'.
Error:
"if(containsAge(doc['unitHolder.units'], params.ages)){",
" ^---- HERE",...
"caused_by": {
"type": "illegal_argument_exception",
"reason": "No field found for [unitHolder.units] in mapping with types [pack]"
}
Request query:
{
"query": {
"bool": {
"must": [
{
"script": {
"script": {
"source": "boolean containsAge(def unit, def ages)
{
if(unit.info.children.minAge != null)
{
int nrAdults = 0;
int nrChildren = 0;
int nrInfants = 0;
for (age in ages)
{
if (age < unit.info.children.maxAge.value)
{
nrAdults++;
}else if(age > unit.info.children.minAge.value)
{
nrInfants++;
}else{
nrChildren++;
}
}
if (nrAdults > 2)
{
return true;
}
}
return false;
}
if(containsAge(doc['unitHolder.units'], params.ages))
{
return true;
}
return false;",
"lang": "painless",
"params": {
"ages": [
50,
35
]
}
}
}
}
]
}
},
"size": 10
}
Mapping:
"mappings": {
"pack": {
"properties": {
"unitHolder": {
"properties": {
"createDate": {
"type": "date"
},
"units": {
"properties": {
"info": {
"properties": {
"children": {
"properties": {
"maxAge": {
"type": "long"
},
"minAge": {
"type": "long"
}
}
}
}
}
}
}
}
}
}
}
}
Upvotes: 1
Views: 3265
Reputation: 411
This is because doc[<fieldName>]
accesses doc-values, so it doesn't work on nested structures. From Elasticsearch documentation:
"Doc-values can only return "simple" field values like numbers, dates, geo- points, terms, etc, or arrays of these values if the field is multi-valued. It can not return JSON objects."
What you need is to put params._source[unitHolder]
into a Map-type variable and then see if that variable contains unit
.
Updated to incl some example:
Map unitHolderMap = params._source['unitHolder`];
if (unitHolderMap.containsKey('units')){
// get the ages from their respective properties and evaluate them
}
Upvotes: 3