# Sort with aggregation with another aggregation in Java REST API

**URL:** https://discuss.elastic.co/t/sort-with-aggregation-with-another-aggregation-in-java-rest-api/273520
**Category:** Elasticsearch
**Created:** [May 20, 2021, 11:52am UTC](https://discuss.elastic.co/t/sort-with-aggregation-with-another-aggregation-in-java-rest-api/273520 "2021-05-20T11:52:01Z")
**Posts on this page:** 3
**Page:** 1

<div class="post-metadata">

### Author: ![Nick\_M](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/nick_m/32/89017_2.png) [@Nick\_M](https://discuss.elastic.co/u/Nick_M)
#### Post date: [May 20, 2021, 11:52am UTC](https://discuss.elastic.co/t/sort-with-aggregation-with-another-aggregation-in-java-rest-api/273520/1 "2021-05-20T11:52:02Z")

</div>

I created the query below and I want to execute it with the Java Client provided but I can't really find a way.

```auto
GET asset-records-latest/_search
{
  "size": 0,
  "aggs": {
    "agg1": {
      "terms": {
        "field": "asset_id",
        "order": {
          "agg2": "desc"
        },
        "size": 10
      },
      "aggs": {
        "agg2": {
          "max": {
            "field": "risk_index_value"
          }
        }
      }
    }
  }
}

```

---

<div class="post-metadata">

### Author: ![dadoonet](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/dadoonet/32/137187_2.png) [@dadoonet](https://discuss.elastic.co/u/dadoonet)
#### Post date: [May 25, 2021, 1:33pm UTC](https://discuss.elastic.co/t/sort-with-aggregation-with-another-aggregation-in-java-rest-api/273520/2 "2021-05-25T13:33:59Z")

</div>

Welcome!

What about:

```auto
SearchResponse response = client.search(new SearchRequest("asset-records-latest").source(new SearchSourceBuilder()
        .size(0)
        .aggregation(AggregationBuilders.terms("agg1")
                .field("asset_id")
                .order(BucketOrder.aggregation("agg2", false))
                .subAggregation(AggregationBuilders.max("agg2").field("risk_index_value"))
        )
), RequestOptions.DEFAULT);

```

---

<div class="post-metadata">

### Author: ![system](https://us1.discourse-cdn.com/elastic/original/3X/1/a/1ac57faf039f6b580b3f104ef42a2a89e41014de.png) [@system](https://discuss.elastic.co/u/system)
#### Post date: [June 22, 2021, 1:34pm UTC](https://discuss.elastic.co/t/sort-with-aggregation-with-another-aggregation-in-java-rest-api/273520/3 "2021-06-22T13:34:47Z")

</div>

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.
