Writing nested aggregation query in NEST

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? 
    }
};

With 6.x, this would be something like

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.

1 Like

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