Sub-aggregation scripts with parameters taken from the parent aggregation
Is there a way to use the key
aggregation list value as a parameter in subaggregation?
Having an index like:
{
"id": 152,
"description": "cool stuff",
"datesWithTotal" : [
{
"date" : "2014-02-02T00:00:00",
"total" : 47.2
},
{
"date" : "2014-02-03T00:00:00",
"total" : 51.2
},
{
"date" : "2014-02-04T00:00:00",
"total" : 56.4
}
]
}
I would like to perform a date_histogram
subaggregation aggregation that will perform some operation based on the current valueparentbucket.key
{
"aggs": {
"histo": {
"date_histogram": {
"field": "datesWithTotal.date",
"interval": "1d"
},
"aggs": {
"script-test": {
"scripted_metric": {
"init_script": "_agg['sum'] = 0",
"map_script": "_agg.sum += (PARENTBUCKET.KEY == 'somevalue' ? 1 : 0)",
"combine_script": "return _agg.sum"
}
}
}
}
}
}
I've already used some scripts this way, but each one didn't use anything from the parent, just simple integer parameters.
source to share
It's just an idea. I tested it quickly, but for some reason not outputting what I thought it should. Perhaps this gives you some additional ideas or you can get it to work in a way I have not been able to do so far:
{
"aggs": {
"histo": {
"date_histogram": {
"field": "datesWithTotal.date",
"interval": "1d"
},
"aggs": {
"doesIncludeDate": {
"terms": {
"script": "new Date(doc[\"datesWithTotal.date\"].value).format(\"yyyy-MM-dd\")",
"valueType": "string",
"include": {
"pattern": "2014-02-04"
}
},
"aggs": {
"script-test": {
"scripted_metric": {
"init_script": "_agg['sum'] = 0",
"map_script": "_agg.sum += 1",
"combine_script": "return _agg.sum"
}
}
}
},
"doesNotIncludeDate": {
"terms": {
"script": "new Date(doc[\"datesWithTotal.date\"].value).format(\"yyyy-MM-dd\")",
"valueType": "string",
"exclude": {
"pattern": "2014-02-04"
}
},
"aggs": {
"script-test": {
"scripted_metric": {
"init_script": "_agg['sum'] = 0",
"map_script": "_agg.sum += 0",
"combine_script": "return _agg.sum"
}
}
}
}
}
}
}
}
The idea is to use the aggregation terms
s include
and more terms
s exclude
to have buckets that match your parent bucket or not. For those that match your script with _agg.sum += 1
for a different use _agg.sum += 0
.
Of course it's all for a very specific script you have: date X or not. If the script is more complex it won't be useful. And I don't think you can access the parent key from within the script (or I haven't found a way to do this).
source to share