elasticsearch 如何使用opensearch java客户端实现嵌套聚合

weylhg0b  于 2022-12-17  发布在  ElasticSearch
关注(0)|答案(1)|浏览(199)

版本

opensearch-rest-client: 2.4.0    
opensearch-java: 2.1.0

问题描述

我只想知道如何使用opensearch-java客户端类实现一个嵌套的聚合来将它添加到一个搜索查询中。下面是我想做的一个例子:

{
      "aggs": {
        "2": {
          "terms": {
            "field": "bytes",
            "order": {
              "_count": "desc"
            },
            "size": 5
          },
          "aggs": {
            "3": {
              "terms": {
                "field": "machine.ram",
                "order": {
                  "_count": "desc"
                },
                "size": 5
              }
            }
          }
        }
      }

我只是想有人解释一下如何将上面的请求转换为opensearch java客户端的方式。

vsikbqxv

vsikbqxv1#

试试这个:

Map<String, Aggregation> map = new HashMap<>();

Aggregation sub_aggregation = new Aggregation.Builder()
    .terms(new TermsAggregation.Builder().field("machine.ram").order(Map.of("_count", SortOrder.Desc)).size(5).build())
    .build();

Aggregation aggregation = new Aggregation.Builder()
    .terms(new TermsAggregation.Builder().field("bytes").order(Map.of("_count", SortOrder.Desc)).size(5).build())
    .aggregations(new HashMap<>() {{
      put("3", sub_aggregation);
    }}).build();

map.put("2", aggregation);

SearchRequest searchRequest = new SearchRequest.Builder()
    .index("idx_name")
    .size(0)
    .aggregations(map)
    .build();

相关问题