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

jre*_*rey 4 java elasticsearch

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

首先我按组织(多租户)过滤,然后按客户分组,最后总结销售量,但我只想拥有 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
                           }
                       }

                  }
               }
           }
     }
 }
 }'
Run Code Online (Sandbox Code Playgroud)

我的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();
}
Run Code Online (Sandbox Code Playgroud)

Ita*_*ayD 5

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

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

还有一件事,如果您想要前 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);

  • 另一件事..我没有找到Terms.Order,但我把.order(BucketOrder.aggregation("sum_total",false))...我想是一样的 (2认同)