六、占比百分位 min,max,sum,avg 统计
func aggsMaxMinSumAvg(index string) {
client :=getCli()
aggsMax :=es.NewMaxAggregation().Field("amount")
aggsMin :=es.NewMinAggregation().Field("amount")
aggsAvg :=es.NewAvgAggregation().Field("amount")
aggsSum :=es.NewSumAggregation().Field("amount")
result, err := client.Search().Index(index).Size(0).Aggregation("avg", aggsAvg).Aggregation("min", aggsMin).Aggregation("sum", aggsSum).Aggregation("max", aggsMax).Do(context.Background())
if err !=nil {
fmt.Println("err:", err)
return
}
min, err := result.Aggregations["min"].MarshalJSON()
fmt.Sprintf("min:%v,%v", string(min), err)
max, err := result.Aggregations["max"].MarshalJSON()
fmt.Sprintf("min:%v,%v", string(max), err)
avg, err := result.Aggregations["avg"].MarshalJSON()
fmt.Sprintf("max:%v,%v", string(avg), err)
sum, err := result.Aggregations["sum"].MarshalJSON()
fmt.Sprintf("sum:%v,%v", string(sum), err)
}
七、按指定字段分类统计
func aggsProName(indexstring) {
client :=getCli()
agg :=es.NewTermsAggregation().Field("proName.keyword")
result, err := client.Search().Index(index).Size(0).Aggregation("proName", agg).Do(context.Background())
if err !=nil {
fmt.Println("err:", err)
return
}
b, err := result.Aggregations["proName"].MarshalJSON()
obj :=AggsProNameCount{}
err =json.Unmarshal(b, &obj)
if err !=nil {
fmt.Println("err:", err)
return
}
for _, v :=range obj.Buckets {
fmt.Sprintf("商品名称:%s,数量:%d", v.Key, v.Count)
}
}
type AggsProNameCount struct { Buckets []struct { Key string `json:"key"` Count int64 `json:"doc_count"` } `json:"buckets"`}
八、按照时间分类,分类后在细分统计
func aggsOrder(index string, start, end int64, fixedInterval string) {
client :=getCli()
query :=es.NewRangeQuery("createTime")
if start !=0 {
query.Gte(start)
}
if end !=0 {
query.Lte(end)
}
amount :=es.NewAvgAggregation().Field("amount")
amountSum :=es.NewSumAggregation().Field("amount")
dayAvg :=es.NewDateHistogramAggregation().Field("createTime").Interval("day").MinDocCount(0).SubAggregation("avg", amount).SubAggregation("sum", amountSum)
da :=es.NewDateHistogramAggregation().Interval(fixedInterval).Field("createTime").MinDocCount(0).SubAggregation("avg", dayAvg)
result, err := client.Search().Index(index).Query(query).Size(0).Aggregation("day", da).Do(context.Background())
if err !=nil {
fmt.Println("err:", err)
return
}
b, err := result.Aggregations["day"].MarshalJSON()
param :=AggsCount{}
err =json.Unmarshal(b, ¶m)
if err !=nil {
fmt.Println("err:", err)
return
}
var sum int64
for _, v :=range param.Buckets {
fmt.Sprintf("time:%d 数量:%d", v.Key,, v.Count)
sum += v.Count
}
fmt.Println("sum:", sum)
}
type AggsCount struct { Buckets []struct { Key int64 `json:"key"` Count int64 `json:"doc_count"` } `json:"buckets"`}