首页 > 其他分享 >go elasticsearch聚合统计

go elasticsearch聚合统计

时间:2024-08-18 10:25:37浏览次数:6  
标签:聚合 err elastic price searchResult elasticsearch go Elasticsearch

在 Go 语言中使用 Elasticsearch 进行聚合统计,你可以使用  olivere/elastic  这个流行的 Elasticsearch 客户端库。以下是一个使用  olivere/elastic  进行聚合统计的示例代码:
首先,你需要安装  olivere/elastic  库:
go get github.com/olivere/elastic
然后,你可以编写如下代码:
package main

import (
    "context"
    "fmt"
    "log"

    "github.com/olivere/elastic"
)

func main() {
    // 创建一个新的 Elasticsearch 客户端
    client, err := elastic.NewClient(
        elastic.SetURL("http://localhost:9200"), // 替换为你的 Elasticsearch 服务地址
        elastic.SetSniff(false),
    )
    if err != nil {
        log.Fatal(err)
    }

    // 检查 Elasticsearch 服务是否可用
    exists, err := client.Ping("http://localhost:9200").Do(context.Background())
    if err != nil {
        log.Fatal(err)
    }
    if !exists {
        log.Fatal("Elasticsearch cluster is down!")
    }

    // 定义聚合查询
    aggs := elastic.NewAggregation() // 聚合
    aggs.Avg("avg_price", "price")   // 计算价格的平均值
    aggs.Sum("sum_price", "price")   // 计算价格的总和
    aggs.Min("min_price", "price")   // 找到价格的最小值
    aggs.Max("max_price", "price")   // 找到价格的最大值

    // 执行搜索查询
    searchResult, err := client.Search("your_index").Size(0) // 替换为你的索引名
        .Aggregation("stats", aggs) // 添加聚合
        .Do(context.Background())

    if err != nil {
        log.Fatal(err)
    }

    // 检查是否有命中
    if searchResult.Hits == nil {
        log.Println("No hits")
    }

    // 打印聚合结果
    fmt.Printf("Found a total of %d aggregation results\n", searchResult.TotalHits())

    // 访问聚合结果
    if avg, found := searchResult.Aggregations.Avg("avg_price"); found {
        fmt.Printf("Average price: %v\n", avg.Value)
    }
    if sum, found := searchResult.Aggregations.Sum("sum_price"); found {
        fmt.Printf("Sum of prices: %v\n", sum.Value)
    }
    if min, found := searchResult.Aggregations.Min("min_price"); found {
        fmt.Printf("Minimum price: %v\n", min.Value)
    }
    if max, found := searchResult.Aggregations.Max("max_price"); found {
        fmt.Printf("Maximum price: %v\n", max.Value)
    }
}
这段代码首先创建了一个 Elasticsearch 客户端,并检查了 Elasticsearch 服务是否可用。然后,它定义了聚合查询,包括平均值、总和、最小值和最大值的聚合,并执行了搜索查询。最后,它打印了聚合的结果。
请确保将  http://localhost:9200  替换为你的 Elasticsearch 服务地址,将  your_index  替换为你的索引名,将  price  替换为你想要聚合的字段名。
最新版本

func Test005_StatsAll(t *testing.T) {
    aggs := elastic.NewStatsAggregation().Field("state") // 聚合

    // 执行搜索查询
    searchResult, err := EsClient().
       Search("dev_biz_grouping_buy_line").Query(elastic.NewMatchAllQuery()).Size(0). // 替换为你的索引名
       Aggregation("stats", aggs).Do(context.Background())

    logrus.Info(jsonutils.ToJsonPretty(searchResult), err)
}

正确答
INFO[2024-08-818 10:05:59]D: {
     "took": 1,
     "hits": {
          "total": {
               "value": 53,
               "relation": "eq"
          }
     },
     "aggregations": {
          "stats": {"count":53,"min":10.0,"max":40.0,"avg":29.245283018867923,"sum":1550.0}
     },
     "_shards": {
          "total": 3,
          "successful": 3,
          "failed": 0
     }
统一封装:
func (this *TestQueryRequestAgg) Test114_EsMax() {

    var request = pagereq.NewQueryRequest()
    request.IndexName = "dev_biz_grouping_buy_line" //request.AttachResp = true
    var result, err = request.EsMax("state").EsQueryResult()
    if err != nil {
       logrus.Error(err)
    }
    logrus.Info(result)
    this.Equal(200, result.Code)
}

执行结果

INFO[2024-08-818 10:12:33]D:/go-ichub/git.ichub.com/webcli120/test/estest/query_request_agg_test.go:424 git.ichub.com/general/webcli120/test/estest.(*TestQueryRequestAgg).Test113_EsStats() {
     "code": 200,
     "msg": "成功",
     "data": {
          "agg_type": 106,
          "key": "",
          "doc_count": 0,
          "stat_field": "state",
          "count": 53,
          "min": 10,
          "max": 40,
          "avg": 29.245283018867923,
          "sum": 1550
     },
     "total": 53,
     "page_size": 20,
     "current": 1

标签:聚合,err,elastic,price,searchResult,elasticsearch,go,Elasticsearch
From: https://blog.csdn.net/leijmdas/article/details/141291558

相关文章