How to use a script field inside Aggregate?

Hi!
I want to use script fields inside Aggregate, I wrote this query:
GET test/_search
{
"size":0,
"query": {
"bool": {
"filter": [
{
"term": {
"eventType": 5
}
},
{
"range": {
"createdDate": {
"gte": "2018-01-01",
"lt": "2019-01-01"
}
}
}
]
}
},
"script_fields": {
"script_sum": {
"script": {
"lang": "painless",
"source": " doc['price'].value * doc['audrate'].value"
}
}
},
"aggs": {
"months": {
"date_histogram": {
"field": "createdDate",
"calendar_interval": "month",
"format": "MM-MMMM"
},
"aggs": {
"test": {
"sum": {
"field": "script_sum"
}
}
}
}
}
}

but the output result does not have any value for the script field "script_sum".
Is it possible to use script fields in aggregates or not?

I am using this version of ES 7.2

Script fields are a feature which produce field values on the fly for the top N documents that match the given query. They are not useable in other parts of the API. In particular, since they are only calculated for top N, it would not be possible to use them for aggregations which operate on every document the query matches.

You will need to duplicate your script inside your sum aggregation. There is a documented example using a script for a sum aggregation which may help. To avoid duplication, you could also store the script and reference in both locations by name.

Thanks for the answer.
We tried to do this, use scripts inside the aggregation, it turned out to be too slow, in the end we abandoned this idea, and transferred the calculation logic to the application.

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