Gianluca Ghettini
Gianluca Ghettini

Reputation: 11658

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?

Upvotes: 1

Views: 2699

Answers (2)

Jack
Jack

Reputation: 59

This is how I accessed my children buckets with nested aggregations.

var yourAgg = result.Aggregations.Terms("YourParentField");
foreach (var child in yourAgg .Buckets)
{
   var aggs = child.Terms("YourChildField").Buckets;
   foreach (var item in aggs)
   {
      perDealerAggItems.Add(new AggregateItem()
        {
              Count = item.DocCount ?? 0,
              Key = item.Key,
              ParentList = field
          });
     }
}

Upvotes: 0

Filip Cordas
Filip Cordas

Reputation: 2561

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}");
             }
         }  

Upvotes: 5

Related Questions