elastic
elastic copied to clipboard
Generating nested histogram query
Please use the following questions as a guideline to help me answer your issue/question without further inquiry. Thank you.
Which version of Elastic are you using?
[x] elastic.v7 (for Elasticsearch 7.x)
I'm having difficulty generating the desired histogram query with sub aggregations.
This is the query I want to generate.
{
"size": 0,
"aggs": {
"range": {
"histogram": {
"field": "counter",
"interval": 2
},
"aggs": {
"nested": {
"nested": {
"path": "deposits"
},
"aggs": {
"scripts": {
"avg": {
"script": {
"lang": "painless",
"source": "return doc['deposits.depositA'].value + doc['deposits.depositB'].value"
}
}
}
}
}
}
}
}
}
You'll have to excuse me if this is a dumb question, since I'm new to both elasticsearch and this package. But this is as far as I've gotten:
nested := NewNestedAggregation().Path("deposits")
scriptq := elastic.NewScriptQuery(NewScript("return doc['deposits.depositA'].value + doc['deposits.depositB'].value"))
hist := NewHistogramAggregation().Field("counter").Interval(2).SubAggregation("avg", scriptq)
client.Search().Index(indexName).Aggregation() ... // this is where I get stuck
I'm not sure of the type of aggregation I can attach in Aggregation()
.
I've been reviewing the _test
files of this package to get some idea on what to do but a lot of this is still going over my head.
Any help would be greatly appreciated.
I solved this with:
scr := elastic.NewScript("return doc['deposits.depositA'].value + doc['deposits.depositB'].value")
avg := elastic.NewAvgAggregation().Script(scr)
nested := elastic.
NewNestedAggregation().
Path("deposits").
SubAggregation("nested", avg)
agg := elastic.
NewHistogramAggregation().
Field("counter").
Interval(50).
SubAggregation("balance", nested)
src, _ := agg.Source()
d, _ := json.MarshalIndent(src, "", " ")
fmt.Println(string(d))
which prints out:
{
"aggregations": {
"balance": {
"aggregations": {
"nested": {
"avg": {
"script": {
"source": "return doc['deposits.depositA'].value + doc['deposits.depositB'].value"
}
}
}
},
"nested": {
"path": "deposits"
}
}
},
"histogram": {
"field": "counter",
"interval": 50
}
}
Which isn't exactly the same as the query above but seems to return the same output on ES.
Can anyone let me now if this is right?