```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 %s\n", code, info.Version.Number)
esversion,err := client.ElasticsearchVersion(host)
if err != nil {
panic(err)
}
fmt.Printf("Elasticsearch version %s\n", 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("处理完成。")
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)