I have a nested field and I want to sum up the values of that nested object using script. I can not use aggregation, as this summation is done for range filtering.
My mappings:
{
"_doc" : {,
"properties" : {
"searchPrices" : {
"type" : "nested",
"properties" : {
"price" : {
"type" : "double"
},
"type" : {
"type" : "keyword"
}
}
}
}
}
}
The query I tried:
{
"size": 100,
"query": {
"bool": {
"must": [
{
"nested": {
"path": "searchPrices",
"query": {
"bool": {
"must": [
{
"script": {
"script": """
int sum = 0;
for (obj in doc['searchPrices.price']) {
sum = sum + obj;
}
sum >= 200;"""
}
},
{
"term": {
"searchPrices.type": "recurringPrice"
}
}
]
}
}
}
}
]
}
}
}
The problem is that this script is only picking the first nested document irrespective of the fact that there are multiple search prices within a document.
Sample doc:
{
"id" : "v2",
"searchPrices" : [
{
"price" : 2000,
"type" : "recurringPrice",
},
{
"price" : 200,
"type" : "recurringPrice",
"conditions" : [
"addon1"
]
},
{
"price" : 400,
"type" : "recurringPrice",
"conditions" : [
"addon2"
]
}
]
}
So, instead of considering 2600 as the price, it is only considering 2000 as the price.