go中 elastic 聚合统计(1)

go调用elastic使用es聚合统计:

1、查询指定金额的订单数

func queryCount(indexstring) {

client :=getCli()

aggsMatch :=es.NewMatchQuery("amount", 1000)

result, err := client.Search().Index(index).

Size(0).Query(aggsMatch).Do(context.Background())

if err !=nil {

fmt.Println("err:", err)

return

}

fmt.Sprintf("count:%v,%v", result.Hits.TotalHits, err)

}

2、字段值汇总和去重复值

func aggeQueryCount(index string) {

client :=getCli()

aggsMatch :=es.NewValueCountAggregation().Field("amount")

aggsCard :=es.NewCardinalityAggregation().Field("amount")

result, err := client.Search().Index(index).

Size(0).Aggregation("val_count", aggsMatch).Aggregation("val_c", aggsCard).Do(context.Background())

if err !=nil {

fmt.Println("err:", err)

return

}

val, err := result.Aggregations["val_count"].MarshalJSON()

fmt.Sprintf("val:%v,%v", string(val), err)

val, err = result.Aggregations["val_c"].MarshalJSON()

fmt.Sprintf("val:%v,%v", string(val), err)

}

三、stats 统计,最大值、最小值、平均值、求和

func aggeStats(index string) {

client :=getCli()

aggsStats :=es.NewStatsAggregation().Field("amount")

result, err := client.Search().Index(index).Size(0).Aggregation("amount", aggsStats).Do(context.Background())

if err !=nil {

fmt.Println("err:", err)

return

}

val, err := result.Aggregations["amount"].MarshalJSON()

fmt.Sprintf("val:%v,%v", string(val), err)

}

四、extended stats 统计,比status多平方和、方差、标准差、平均值加/减两个标准差的区间

func aggeExtendedStats(index string) {

client :=getCli()

aggsStats :=es.NewExtendedStatsAggregation().Field("amount")

result, err := client.Search().Index(index).Size(0).Aggregation("amount", aggsStats).Do(context.Background())

if err !=nil {

fmt.Println("err:", err)

return

}

val, err := result.Aggregations["amount"].MarshalJSON()

fmt.Sprintf("val:%v,%v", string(val), err)

}

五、占比百分位

func aggsPercentiles(index string) {

client :=getCli()

aggs :=es.NewPercentilesAggregation().Field("amount")

result, err := client.Search().Index(index).Size(0).Aggregation("amount", aggs).Do(context.Background())

if err !=nil {

fmt.Println("err:", err)

return

}

val, err := result.Aggregations["amount"].MarshalJSON()

fmt.Sprintf("val:%v,%v", string(val), err)

}

你可能感兴趣的:(go中 elastic 聚合统计(1))