Search code examples
c#elasticsearchnest

Get Elasticsearch result from a NEST C# nested aggregation


I have this Elasticsearch NEST query:

var res = elastic.Search<SegmentRecord>(s => s.Index(esIndex).Aggregations(a => a.Terms("agg", x => x.Field(o => o.InstrumentName).Aggregations(a1 => a1.Terms("agg2", f => f.Field(y => y.GroupId))))));

how can I cycle through all the InstrumentName fields, and for each of those, cycle through all the GroupId fields?


Solution

  • On Nest 5.4.0

    foreach (var bucket in res.Aggs.Terms("agg").Buckets)
             {
                 foreach (var innerBucket in bucket.Terms("agg2").Buckets)
                 {
                     System.Console.WriteLine($"agg:{bucket.Key}, agg2:{innerBucket.Key} - {innerBucket.DocCount}");
                 }
             }