go elasticsearch实现分组统计求和

在Go语言中使用 olivere/elastic 库实现分组聚合统计,你可以使用 TermsAggregation 来对某个字段进行分组,并在每个分组内部使用其他聚合类型(如 SumAggregation )进行统计。以下是一个示例,展示如何对 category 字段进行分组,并在每个分组内部计算 price 字段的总和:
首先,确保你已经安装了 olivere/elastic 库。如果还没有安装,可以使用以下命令安装:
go get github.com/olivere/elastic/v7
以下是使用 olivere/elastic 库实现分组聚合统计的示例代码:
package main

import (
    "context"
    "fmt"
    "log"

    "github.com/olivere/elastic/v7"
)

func main() {
    // 创建一个Elasticsearch客户端
    client, err := elastic.NewClient(
        elastic.SetURL("http://localhost:9200"),
        elastic.SetSniff(false), // 禁用自动嗅探
    )
    if err != nil {
        log.Fatalf("Error creating client: %s", err)
    }

    // 检查Elasticsearch是否可达
    exists, err := client.Ping("http://localhost:9200").Do(context.Background())
    if err != nil {
        log.Fatalf("Ping error: %s", err)
    }
    if !exists {
        log.Fatal("Elasticsearch is not running on http://localhost:9200")
    }

    // 定义搜索请求体
    searchResult, err := client.Search("my_index").Type("_doc") // 替换为你的索引名和类型
        .Size(0) // 不需要原始文档
        .Aggregation("price_by_category", elastic.NewTermsAggregation().Field("category").Size(0) // 分组字段
            .SubAggregation("total_price", elastic.NewSumAggregation().Field("price"))) // 分组内部的聚合
        .Do(context.Background())

    if err != nil {
        log.Fatalf("Search error: %s", err)
    }

    // 检查是否有错误
    if searchResult.IsError() {
        log.Fatalf("Error: %s", searchResult.String())
    }

    // 获取分组聚合结果
    termsAgg, found := searchResult.Aggregations.Terms("price_by_category")
    if !found {
        log.Fatal("Terms aggregation not found")
    }

    // 打印每个分组的统计结果
    for _, bucket := range termsAgg.Buckets {
        fmt.Printf("Category: %s\n", bucket.Key)
        sumAgg, found := bucket.Sum("total_price")
        if found {
            fmt.Printf("  Total Price: %v\n", sumAgg.Value())
        }
    }
}
这段代码首先创建了一个Elasticsearch客户端,并检查Elasticsearch服务是否可达。然后,定义了一个搜索请求体,使用 elastic.NewTermsAggregation().Field("category") 来定义一个基于 category 字段的分组聚合,并设置 .Size(0) 来指示不需要返回文档计数。在每个分组内部,使用 elastic.NewSumAggregation().Field("price") 来定义一个求和聚合,计算 price 字段的总和。
最后,执行搜索请求并获取分组聚合结果,然后遍历每个分组的桶(bucket),打印出每个分组的名称和对应的价格总和。
请注意,你需要根据你的Elasticsearch服务的实际URL、索引名称、类型和字段进行相应的调整。此外,确保你的索引中有一个名为 category 的字段,并且该字段的类型适合进行分组操作,同时 price 字段的类型适合进行求和操作。
 

  • 7
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

leijmdas

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值