Home > Mobile >  How to implement nested aggregations using opensearch java client
How to implement nested aggregations using opensearch java client

Time:12-17

Versions

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

Issue Description

I just want to know how to implement a nested aggregation to add it to a search query using the opensearch-java client classes. Below there is an example of what I want to do:

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

I just want someone to explain how to translate the request above to the opensearch java client way.

CodePudding user response:

Try this:

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();
  • Related