Aggregation examples
This page demonstrates how to use aggregations.
var response = await client.SearchAsync<Person>(search => search .Indices("persons") .Query(query => query .MatchAll() ) .Aggregations(aggregations => aggregations .Add("agg_name", aggregation => aggregation .Max(max => max .Field(x => x.Age) ) ) ) .Size(10) );
var response = await client.SearchAsync<Person>(new SearchRequest("persons") { Query = new Query { MatchAll = new MatchAllQuery() }, Aggregations = new Dictionary<string, Aggregation> { { "agg_name", new Aggregation { Max = new MaxAggregation { Field = Infer.Field<Person>(x => x.Age) } }} }, Size = 10 });
var max = response.Aggregations!.GetMax("agg_name")!; Console.WriteLine(max.Value);
var response = await client.SearchAsync<Person>(search => search .Indices("persons") .Query(query => query .MatchAll(_ => {}) ) .Aggregations(aggregations => aggregations .Add("firstnames", aggregation => aggregation .Terms(terms => terms .Field(x => x.FirstName) ) .Aggregations(aggregations => aggregations .Add("avg_age", aggregation => aggregation .Max(avg => avg .Field(x => x.Age) ) ) ) ) ) .Size(10) );
- The top level
Terms
aggregation with namefirstnames
. - Nested aggregation of type
Max
with nameavg_age
.
var response = await client.SearchAsync<Person>(new SearchRequest<Person> { Query = new Query { MatchAll = new MatchAllQuery() }, Aggregations = new Dictionary<string, Aggregation> { { "firstnames", new Aggregation { Terms = new TermsAggregation { Field = Infer.Field<Person>(x => x.FirstName) }, Aggregations = new Dictionary<string, Aggregation> { { "avg_age", new Aggregation { Max = new MaxAggregation { Field = Infer.Field<Person>(x => x.Age) } }} } }} } });
var firstnames = response.Aggregations!.GetStringTerms("firstnames")!; foreach (var bucket in firstnames.Buckets) { var avg = bucket.Aggregations.GetAverage("avg_age")!; Console.WriteLine($"The average age for persons named '{bucket.Key}' is {avg}"); }