Aggregations
This page covers how to run aggregations with the Go client. For the full aggregations reference, see Aggregations in the Elasticsearch documentation.
Given documents with a price field, we run a sum aggregation on index_name.
query := `{
"size": 0,
"aggs": {
"total_prices": {
"sum": {
"field": "price"
}
}
}
}`
res, err := client.Search(
client.Search.WithIndex("index_name"),
client.Search.WithBody(strings.NewReader(query)),
)
if err != nil {
log.Fatal(err)
}
defer res.Body.Close()
- Specifies the index name.
- Pass the aggregation query as raw JSON. Setting
"size": 0retrieves only the aggregation result.
The some package provides helpers for inline pointers on primitive types:
import "github.com/elastic/go-elasticsearch/v9/typedapi/some"
totalPricesAgg, err := es.Search().
Index("index_name").
Request(
&search.Request{
Size: some.Int(0),
Aggregations: map[string]types.Aggregations{
"total_prices": {
Sum: &types.SumAggregation{
Field: some.String("price"),
},
},
},
},
).Do(context.Background())
- Specifies the index name.
- Sets the size to 0 to retrieve only the result of the aggregation.
- Specifies the field name on which the sum aggregation runs.
- The
SumAggregationis part of theAggregationsmap.
The esdsl aggregation builders let you define aggregations with a fluent syntax:
import "github.com/elastic/go-elasticsearch/v9/typedapi/esdsl"
totalPricesAgg, err := es.Search().
Index("index_name").
Size(0).
AddAggregation("total_prices",
esdsl.NewSumAggregation().Field("price"),
).
Do(context.Background())
- Specifies the index name.
- Sets the size to 0 to retrieve only the result of the aggregation.
- Names the aggregation
total_prices. NewSumAggregation()creates a sum aggregation builder - chain.Field()to set the target field.