英文:
Write simple ES avg aggregation in golang
问题
我一直在尝试用GO语言编写一个简单的ES平均聚合,但是尽管听起来很简单,我不确定如何解析结果:
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
}
// 解析结果
aggs := searchResult.Aggregations
但是我不确定如何解析searchResult
以获取这个聚合的结果。基本上,我想解析一批表示学生的文档,并获取作业平均大小。
英文:
I've been trying to write a simple ES avg aggregation in GO but even though this sound I am not sure 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 am not sure how to parse searchResult
to get the result of this aggregation. Basically I want to parse a bulk of documents representing a Student and get the average size of a homework.
答案1
得分: 1
我通常使用http来访问elastic。所以我将结果作为map返回,可以使用调试器检查结果并从那里开始工作。
var resp map[string]interface{}
err := c.handleRequest(http.MethodGet, tag, req, &resp)
其中tag是你的索引,req是你发送给elastic的请求,resp是响应。
在处理程序中,代码如下:
req, err := http.NewRequest(method, c.endpoint+tag, bytes.NewReader(jsonBody))
其中jsonBody是你传递给处理程序的req。
其他部分是使用go发送http请求的常规方式。
还有一件事要记住,就是在结果map中处理类型(类型断言),代码如下:
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),
}
}
英文:
I'm using http to get to elastic usually. So I return result as map and it's possible to check with debugger what is your result and work from there.
var resp map[string]interface{}
err := c.handleRequest(http.MethodGet, tag, req, &resp)
where tag is your index, req - request you are doing to elastic, and response is response
inside handler it looks like this:
req, err := http.NewRequest(method, c.endpoint+tag, bytes.NewReader(jsonBody))
where jsonBody is req you passed to handler
everything else is usual way to send http with go
one more thing to keep in mind is handling types(type assertions) in resulting map like so:
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),
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论