栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 前沿技术 > 大数据 > 大数据系统

GO操作Elasticsearch,取最大值,最小值,平均值。

GO操作Elasticsearch,取最大值,最小值,平均值。

GO操作Elasticsearch,取最大值,最小值,平均值
```go
package main

import (
	"context"
	"fmt"
	"github.com/olivere/elastic/v7"
)

var client *elastic.Client
var host = "http://192.168.204.111:9200"

//初始化
func init() {
	//errorlog := log.New(os.Stdout, "APP", log.LstdFlags)
	var err error
	//这个地方有个小坑 不加上elastic.SetSniff(false) 会连接不上
	client, err = elastic.NewClient(elastic.SetSniff(false), elastic.SetURL(host))
	if err != nil {
		panic(err)
	}
	_,_,err = client.Ping(host).Do(context.Background())
	if err != nil {
		panic(err)
	}
	//fmt.Printf("Elasticsearch returned with code %d and version %sn", code, info.Version.Number)

	esversion,err := client.ElasticsearchVersion(host)
	if err != nil {
		panic(err)
	}
	fmt.Printf("Elasticsearch version %sn", esversion)

}


func GetMax()  {
	maxa := elastic.NewMaxAggregation().Field("ruKouShiJian")
	res, err := client.Search("cheliangguiji").Size(0).Aggregation("max",maxa).Do(context.Background())
	if err != nil{
		fmt.Println(err)
	}else{
		v,a := res.Aggregations.ValueCount("max")
		if a{
			maxValue := string(v.Aggregations["value_as_string"])
			fmt.Println("maxvalue=",maxValue)
		}
	}
}


func GetMin()  {
	mina := elastic.NewMinAggregation().Field("ruKouShiJian")
	res, err := client.Search("cheliangguiji").Size(0).Aggregation("min",mina).Do(context.Background())
	if err != nil{
		fmt.Println(err)
	}else{
		v,a := res.Aggregations.ValueCount("min")
		if a{
			maxValue := string(v.Aggregations["value_as_string"])
			fmt.Println("minvalue=",maxValue)
		}
	}
}


func GetAvg()  {
	avga := elastic.NewAvgAggregation().Field("jiFeiJinE")
	//这里可以增加其他查询条件
	res, err := client.Search("cheliangguiji").Size(0).Aggregation("avg",avga).Do(context.Background())
	if err != nil{
		fmt.Println(err)
	}else{
		v,a := res.Aggregations.ValueCount("avg")
		if a{
			//v.Aggregations是一个map类型,key根据查询内容不同而不同,需要注意
			avgValue := string(v.Aggregations["value"])
			fmt.Println("minvalue=",avgValue)
		}
	}
}


func main() {
	GetMax()
	GetMin()
	GetAvg()
	fmt.Println("处理完成。")
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/612393.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号