Search code examples
elasticsearchnest

Combining fluent and object initializer syntax


Using the .NET client NEST, is it possible to combine the two syntaxes like below where the Query is written in one syntax and the Aggregation in another?

var request = new SearchRequest();
request.Query = new MatchAllQuery();
request.Aggregations = new AggregationContainerDescriptor<Car>().Terms("color", x => x.Field(doc => doc.Color));
_elasticClient.Search<Car>(request);

The compile error here being that a AggregationContainerDescriptor is not assailable to a AggregationDictionary


Solution

  • You can cast your descriptor to IAggregationContainer and get Aggregations from there:

    var request = new SearchRequest();
    request.Query = new MatchAllQuery();
    var aggregationContainer = (IAggregationContainer)new AggregationContainerDescriptor<Car>().Terms("color", x => x.Field(doc => doc.Color));
    request.Aggregations = aggregationContainer.Aggregations;
    var searchResponse = _elasticClient.Search<Car>(request);
    

    Hope that helps.