Home >Backend Development >Golang >Writing simple ES avg aggregation in golang
php editor Xiaoxin today brought you an article about using Golang to write a simple ES avg aggregation. ES (Elasticsearch) is an open source distributed search and analysis engine that provides rich aggregation functions, including avg (average) aggregation. This article will introduce how to use Golang to write a simple ES avg aggregation program to help everyone better understand and apply the aggregation function of ES. Let’s find out together!
I've been trying to write a simple es avg aggregation in go, but even though this sounds like I don't know how to parse the result:
ctx, cancel := context.WithTimeout(context.Background(), defaultTimeout) defer cancel() query := elastic.NewAvgAggregation().Field("Assignment.HomeworkSize") ss := elastic.NewSearchSource().Query(query) searchResult, err := c.ES.Search().Index(StudentIndex).SearchSource(ss).Do(ctx) if err != nil { return 0, err } // Parse Results aggs := searchResult.Aggregations
But I'm not sure how to parse the searchresult
to get the results of this aggregation. Basically I want to parse a large number of documents representing students and get the average size of the assignments.
I usually use http to access elastic. So I return the results as a map and you can use the debugger to check what your results are and work from there.
var resp map[string]interface{} err := c.handlerequest(http.methodget, tag, req, &resp)
Where tag is your index, req - your request for elastic execution, response is the response
The internal handler looks like this:
req, err := http.newrequest(method, c.endpoint tag, bytes.newreader(jsonbody))
where jsonbody is the request you pass to the handler Everything else is the usual way of sending http with go
One more thing to remember is to handle types (type assertions) in the result map, like this:
for index, hit := range resp["hits"].(map[string]interface{})["hits"].([]interface{}) { Source := hit.(map[string]interface{})["_source"].(map[string]interface{}) items[index] = someType{ SomeField: Source["app_name"].(string), } }
The above is the detailed content of Writing simple ES avg aggregation in golang. For more information, please follow other related articles on the PHP Chinese website!