How to Implement order in terms aggregation in Elastic Search using Java API client

50 views Asked by At

have developed springboot microservice and want to implement below query in elastic search using Java API client, have tried the code attached below, how to implement order inside terms aggregation using java api client and Search Request:

Elastic search: 8.7

  "terms": {
        "field": "metaData.Id",
        **"order": { "max_date": "desc" },**

Attaching Implementation using Java API client and springboot :

    SourceConfig sourceConfig = SourceConfig.of(s -> s.filter(f -> f.includes(Constants.DETAILS)));
    MaxAggregation max_date = MaxAggregation.of(mg -> mg.field(Constants.DATE1));
    TermsAggregation termsAggregation = TermsAggregation.of(t -> t.field(Constants.ID)
            .size(RequestDTO.getNumberOfRecordsPerMatch()));
    TopHitsAggregation topHitsAggregation = TopHitsAggregation
            .of(t -> t.size(1).source(sourceConfig).sort(getSortOptions()));



    Aggregation groupByIdAggregation = Aggregation.of(agg -> agg.terms(termsAggregation)
            .aggregations(Constants.MAX_DATE, max -> max.max(max_date))
            .aggregations(Constants.TOP_DOC, top -> top.topHits(topHitsAggregation)));

    SearchRequest searchRequest = SearchRequest.of(b -> b
                .index(indexname))
                .size(0).query(q -> q.bool(getBooleanQuery(RequestDTO, false)))
                .aggregations(Constants.GROUP_BY_ID,
                        groupByIdAggregation));

Elastic Search Query :

POST /Index/_search?typed_keys=true

{
  "size": 0,
  "query": {
    "bool": {
      "must": [
        {
          "terms": {
            "itemDetails.id": [
              "30773"
            ]
          }
        },
        {
          "range": {
            "metaData.date1": {
              "lte": "2023-10-25T19:55:54.611Z",
              "gte": "2023-10-10T19:55:54.611Z"
            }
          }
        }
      ]
    }
  },
  "aggs": {
    "distinct_Ids": {
      "terms": {
        "field": "metaData.Id",
        "order": { "max_date": "desc" },
        "size": 1
 
      },
      "aggs": {
                "max_date": { 
          "max": { "field": "metaData.Date1" } 
        },
 
        
        "top_doc": {
          "top_hits": {
            "size": 1, 
            "sort": [
              {
                "metaData.Date2": {
                  "order": "desc"
                }
              },
              {
                "metaData.Date1": {
                  "order": "desc"
                }
              }
            ],
            "_source": {
              "includes": [
     
              ]
            }
          }
        }
      }
    }
  }
}
0

There are 0 answers