elasticsearch/opensearch中如何对复合聚合进行排序?

问题描述 投票:0回答:1

我在我的 Spring Boot 应用程序中使用 opensearch-java 库。我想要执行复合聚合,并且需要根据聚合字段之一按降序对最终结果进行排序。下面是我的代码

private SearchRequest buildSearchRequest(SelectedFilters filters) {
  BoolQuery.Builder boolQueryBuilder = QueryBuilders.bool();
 
 Aggregation aggregation1 = new Aggregation.Builder()
          .terms(aggField -> aggField
                  .field("fieldA.keyword")
                  .order(Map.of("_key", SortOrder.Desc))            // Sorting here      
          )
          .build();
  Aggregation aggregation2 = new Aggregation.Builder()
          .terms(aggField -> aggField
                  .field("fieldB"))
          .build();

  CompositeAggregationSource compositeAggregationSource1 = new CompositeAggregationSource.Builder()
          .terms(aggregation1.terms())
          .build();

  CompositeAggregationSource compositeAggregationSource2 = new CompositeAggregationSource.Builder()
          .terms(aggregation2.terms())
          .build();

  Map<String, CompositeAggregationSource> compositeAggregation1 = new HashMap<>();
  compositeAggregation1.put("fieldA_agg", compositeAggregationSource1);

  Map<String, CompositeAggregationSource> compositeAggregation2 = new HashMap<>();
  compositeAggregation2.put("fieldB_agg", compositeAggregationSource2);

  List<Map<String, CompositeAggregationSource>> list = new ArrayList<>();
  list.add(compositeAggregation1);
  list.add(compositeAggregation2);

  Aggregation compositeAggregation = new CompositeAggregation.Builder()
          .sources(list)
          .size(1000)
          .build()
          ._toAggregation();

  return new SearchRequest.Builder()
          .index("my-index")
          .query(boolQueryBuilder.build().toQuery())
          .aggregations("my_bucket", compositeAggregation)
          .size(0)
          .build();
}

对于这段代码,我得到以下结果:

[x_content_parse_exception] [1:125] [composite] failed to parse field [sources]

但是,如果我只是删除订单(Map.of(“_key”,SortOrder.Desc)),我会得到结果,但不是以排序的方式。 我的代码需要进行哪些更改才能使其正常工作??

PS:如果我直接查询 opensearch,它也不起作用。 (他们的自动完成功能也建议采用这种格式,但它并不简单!)

"terms": {
  "field": "fieldA.keyword",
  "order": {
    "_key": "asc"
  }
}

但是如果我这样跑,那么它就会起作用

"terms": {
  "field": "fieldA.keyword",
  "order": "desc"
}

然而,java 客户端类只需要 Map 类(Map),因此无法在应用程序代码中以某种方式做到这一点。

java spring-boot aggregation opensearch
1个回答
0
投票

该问题可能源于以下事实:当在复合源中指定

CompositeAggregationSource
时,TermsAggregation
需要
terms
,即指定独立 
TermsAggregation
聚合时使用的相同
terms
结构。
TermsAggregation
有不同的方式提供排序顺序,即使用
List<Map<String, SortOrder>>

在服务器端,

TermsValuesSourceBuilder
需要一个简单的
SortOrder

PS:我评论了你的票

© www.soinside.com 2019 - 2024. All rights reserved.