Example shows simple Elasticsearch aggregation in golang program – count distinct values for given term and show results in alphabetical order.

package main

import (
	"log"

	"fmt"

	elastic "gopkg.in/olivere/elastic.v3"
)

func main() {

	client, err := elastic.NewClient()
	if err != nil {
		log.Fatal("Cannot create ES client:", err)
	}

	var search *elastic.SearchService

	agg := elastic.NewTermsAggregation().Field("myterm").Size(10000).OrderByTermAsc()

	search = client.Search().Index("myindex").Type("mytype")
	search = search.Aggregation("myterm", agg)

	sr, err := search.Do()
	if err != nil {
		log.Fatal("error in aggregation Do:", err)
	}

	if agg, found := sr.Aggregations.Terms("myterm"); found {
		for _, bucket := range agg.Buckets {
      fmt.Println("key:", bucket.Key, ", count:", bucket.DocCount)
		}
	}

}