# Writing nested aggregation query in NEST

**URL:** <https://discuss.elastic.co/t/writing-nested-aggregation-query-in-nest/179547>\
**Category:** Elasticsearch\
**Created:** [May 3, 2019, 2:00pm UTC](https://discuss.elastic.co/t/writing-nested-aggregation-query-in-nest/179547 "2019-05-03T14:00:17Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Hooman\_Bahreini](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/hooman_bahreini/32/29500_2.png) [@Hooman\_Bahreini](https://discuss.elastic.co/u/Hooman_Bahreini)\
**Post date:** [May 3, 2019, 2:00pm UTC](https://discuss.elastic.co/t/writing-nested-aggregation-query-in-nest/179547/1 "2019-05-03T14:00:17Z")

</div>

How can I convert the following query to NEST?

```
 "aggs": {
    "UnitAggregationBucket": {
      "terms": {
        "field": "unitId",
        "size": 10,
        "order": {
          "max_score": "desc"
        }
      },
      "aggs": {
        "max_score": {
          "max": {
            "script": "_score"
          }
        }
      }
    }

```

This is what I have tried:

```
var unitAggregations = new TermsAggregation(SiteConstants.UnitAggregationBucket)
{
    Size = 10,
    Field = Field<MyDocument>(p => p.UnitId),
    Order = new List<TermsOrder>
    {
        // don't know how to write the max_score? 
    }
};
```

---

<div class="post-metadata">

**Author:** ![forloop](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/forloop/32/9021_2.png) [@forloop](https://discuss.elastic.co/u/forloop)\
**Post date:** [May 8, 2019, 8:03am UTC](https://discuss.elastic.co/t/writing-nested-aggregation-query-in-nest/179547/2 "2019-05-08T08:03:05Z")

</div>

With 6.x, this would be something like

```auto
var client = new ElasticClient();

var searchResponse = client.Search<object>(s => s
	.Aggregations(a => a
		.Terms("UnitAggregationBucket", t => t
			.Field("unitId")
			.Size(10)
			.Order(o => o
				.Descending("maximum_score")
			)
			.Aggregations(aa => aa
				.Max("maximum_score", m => m
					.Script("_score")
				)
			)
		)
	)
);

var termsAgg = searchResponse.Aggregations.Terms("UnitAggregationBucket");

foreach(var bucket in termsAgg.Buckets)
{
	// do something with buckets
	var maxScore = bucket.Max("maximum_score").Value;
}

```

Note that you can't use `max_score` for the name of the aggregation as it's a reserved keyword name in the client, which the client uses in its heuristics based aggregation response JSON deserialization method.

---

<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 5, 2019, 8:03am UTC](https://discuss.elastic.co/t/writing-nested-aggregation-query-in-nest/179547/3 "2019-06-05T08:03:18Z")

</div>

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