Loading

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()
		
  1. Specifies the index name.
  2. Pass the aggregation query as raw JSON. Setting "size": 0 retrieves 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())
		
  1. Specifies the index name.
  2. Sets the size to 0 to retrieve only the result of the aggregation.
  3. Specifies the field name on which the sum aggregation runs.
  4. The SumAggregation is part of the Aggregations map.

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())
		
  1. Specifies the index name.
  2. Sets the size to 0 to retrieve only the result of the aggregation.
  3. Names the aggregation total_prices.
  4. NewSumAggregation() creates a sum aggregation builder - chain .Field() to set the target field.