0
votes

I am looking for how to init a SearchRequest Object with several no nested Aggregations by using the object initializer syntax.

If the request were given as param into ElasticClient.Search() with lambda expression helper it would be written like bellow:

   var response = Client.Search<person>(s => s.Aggregations(a => 
            a.Terms("bucketAge", t => t.Field("age").Size(50))
             .Terms("bucketCity", t => t.Field("city").Size(50))));

What is paradoxical is i found i how to write a Agg with a nested Agg

 var searchRequest = new SearchRequest<person>
        {
            Size = 0,
            Aggregations =
           new TermsAggregation("bucketAge")
           {
               Field = "age",
               Size = 50,
               Aggregations = new TermsAggregation("bucketcity")
               {
                   Field = "city",
                   Size = 50
             }
           }
        };

But i fail to init SearchRequest with 2 aggs on same level with Something like that:

var searchRequest = new SearchRequest<person>
{
        Size = 0,
        Aggregations =
        {
              new TermsAggregation("bucketAge")
              {
                  Field = "age",
                  Size = 50
              },
              new TermsAggregation("bucketcity")
              {
                  Field = "city",
                  Size = 50
              }
         }
 };

How to do this please?

1

1 Answers

2
votes

With the Object Initializer syntax, you can combine aggregations with &&

var searchRequest = new SearchRequest<person>
{
    Size = 0,
    Aggregations =
      new TermsAggregation("bucketAge")
      {
          Field = "age",
          Size = 50
      } &&
      new TermsAggregation("bucketcity")
      {
          Field = "city",
          Size = 50
      }

};

var searchResponse = client.Search<person>(searchRequest);

You can use the longer winded method using an aggregation dictionary if you prefer

var aggregations = new Dictionary<string, AggregationContainer>
{
    { "bucketAge", new TermsAggregation("bucketAge")
      {
          Field = "age",
          Size = 50
      }
    },
    { "bucketcity", new TermsAggregation("bucketcity")
      {
          Field = "city",
          Size = 50
      }
    },
};

var searchRequest = new SearchRequest<person>
{
    Size = 0,
    Aggregations = new AggregationDictionary(aggregations)
};

var searchResponse = client.Search<person>(searchRequest);

Note that the keys in the Dictionary<string, AggregationContainer> will be the names of the aggregations in the request.