Migrating from Elastic NEST v7 to .NET Elastic Client v9: Aggregation with Nested clause

I’m moving code from the NEST client to the Elasticsearch client v9.2. I’m trying to generate aggregation that contains a nested filter. Here is sample of the old code with NEST:
AggregationContainerDescriptor<T> ret;
BoolQueryDescriptor<T> productFilter = new BoolQueryDescriptor<T>();
AggregationContainerDescriptor<T> SKUAggregation = new AggregationContainerDescriptor<T>();

ret = ret
.Filter(FILTER_NAME, f => f
.Filter(sf => sf
.Bool(sfb => productFilter)
)
.Aggregations(fa => fa
.Nested(SKU_NAME, fan => fan
.Path(SKUS_NAME)
.Aggregations(skua => SKUAggregation)
)
)
);

In other words, I need to apply a filter on the main document and then apply an additional filter on a nested document property.

Document sample:
{
“product_name”: “apple”,
“skus”: [
{
“color”: “green”
“price”: 11.99
}
{
“color”: “red”
“price”: 8.45
}
{
“color”: “yellow”
“price”: 9.99
}
]
}

I’ve asked several AIs how this code could be transformed, and they usually return examples similar to the following:

var ret = new Dictionary<string, Aggregation> { { FILTER_NAME, new FilterAggregation { // Apply the PRODUCT LEVEL FILTER Filter = productFilter, // Define the NESTED Aggregation hierarchy Aggregations = new Dictionary<string, Aggregation> { { SKU_NAME, new NestedAggregation { Path = SKUS_NAME, // Nest the previously built SKU aggregations Aggregations = SKUAggregation } } } } } 

However, the problem is that NestedAggregation does not have an Aggregations property in Elasticsearch 9.2.

So if anyone knows how to properly build this using the new client, I would be really thankful.

Hi @Vadym_Romanenko ,

the usage of sub aggregations is documented here:

https://www.elastic.co/docs/reference/elasticsearch/clients/dotnet/aggregations#_object_initializer_api_2

Basically, change this part a little bit:

new Aggregation { Nested = new NestedAggregation { Path = SKUS_NAME }, // Nest the previously built SKU aggregations Aggregations = SKUAggregation } 
1 Like

Thank you, Florain! That helped.

1 Like