Ordering terms in term aggregation in the new Java API Client

I have such an aggregation query in the old High Rest Client and want to convert it into the same query in the new Java API Client but there is not sort function in the terms query. How can we convert it? Or is it by default integrated?

"aggregations": {
        "DOC_TYPE": {
            "filter": {
                "bool": {
                    "adjust_pure_negative": true,
                    "boost": 1
                }
            },
            "aggregations": {
                "DOC_TYPE": {
                    "terms": {
                        "field": "doc_type",
                        "size": 50,
                        "min_doc_count": 1,
                        "shard_min_doc_count": 0,
                        "show_term_doc_count_error": false,
                        "order": [
                            {
                                "_count": "desc"
                            },
                            {
                                "_key": "asc"
                            }
                        ]
                    }
                }
            }
        }
    }

Hi @PodarcisMuralis

I think it could be like this:

 new Aggregation.Builder()
        .terms(new TermsAggregation.Builder()
            .field("doc_type")
            .order(NamedValue.of("_count", SortOrder.Asc), NamedValue.of("_key", SortOrder.Asc))
            .size(5).build())
        .build();

Thanks but I need to maintain this pattern in code and I could not create the order part.

 Aggregation aggregation = Aggregation.of(agg -> agg
                .filter(filter -> filter
                        .bool(bool -> bool))
                .aggregations(aggregationName, subAggregation -> subAggregation
                        .terms(terms -> terms
                                .field(fieldName)
                                .size(50)
                                .minDocCount(1)
                                .showTermDocCountError(false))));
    .terms(term -> term
        .field("doc_type")
        .size(50)
        .minDocCount(1)
        .showTermDocCountError(false)
        .order(NamedValue.of("_count", SortOrder.Asc), NamedValue.of("_key", SortOrder.Asc))
    )
1 Like

Ah my bad, I was indenting in the wrong curly brace.
Thanks a lot!