gpt4 book ai didi

java - 如何将桶排序添加到查询聚合

转载 作者:行者123 更新时间:2023-11-29 02:55:59 24 4
gpt4 key购买 nike

我有一个运行良好的 ElasticSearch 查询 (curl),这是我的第一个查询,

首先我按组织( Multi-Tenancy )过滤,然后按客户分组,最后对销售额求和,但我只想拥有 3 个最好的客户。

我的问题是.. 如何使用 AggregationBuilders 构建聚合以获得“bucket_sort”语句。我使用 Java API 按客户进行销售分组。

弹性查询是:

 curl -X POST 'http://localhost:9200/sales/sale/_search?pretty'  -H 'Content-Type: application/json' -d '
{
"aggs": {

"filtered": {
"filter": {
"bool": {
"must": [
{
"term": {
"organization_id": "15"
}
}
]
}
},
"aggs": {
"by_customer": {
"terms": {
"field": "customer_id"
},
"aggs": {
"sum_total" : {
"sum": {
"field": "amount"
}
},
"total_total_sort": {
"bucket_sort": {
"sort": [
{"sum_total": {"order": "desc"}}
],
"size": 3
}
}

}
}
}
}
}
}'

我的 Java 代码:

@Test
public void queryBestCustomers() throws UnknownHostException {
Client client = Query.client();
AggregationBuilder sum = AggregationBuilders.sum("sum_total").field("amount");
AggregationBuilder groupBy = AggregationBuilders.terms("by_customer").field("customer_id").subAggregation(sum);
AggregationBuilder aggregation =
AggregationBuilders
.filters("filtered",
new FiltersAggregator.KeyedFilter("must", QueryBuilders.termQuery("organization_id", "15"))).subAggregation(groupBy);

SearchRequestBuilder requestBuilder = client.prepareSearch("sales")
.setTypes("sale")
.addAggregation(aggregation);
SearchResponse response = requestBuilder.execute().actionGet();
}

最佳答案

希望我答对了你的问题。尝试将“order”添加到您的 groupBy agg:

AggregationBuilder groupBy = AggregationBuilders.terms("by_customer").field("customer_id").subAggregation(sum).order(Terms.Order.aggregation("sum_total", false));

还有一件事,如果你想要前 3 个客户端而不是你的 .size(3) 也应该在 groupBy agg 上设置而不是在排序上。像那样:
AggregationBuilder groupBy = AggregationBuilders.terms("by_customer").field("customer_id").subAggregation(sum).order(Terms.Order.aggregation("sum_total", false)).size(3);

关于java - 如何将桶排序添加到查询聚合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53023416/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com