3

I want to achieve the equivalent of below SQL query in Elastic:

select BookId, PubDate, count(1)
from BookMessages
where BookId in (1,2)
group by BookId, PubDate

Hence I wrote the below query in C#

var searchresponse = client.Search<BookMessages>(s => s
        .Query(q => q
        .Bool(bq => bq
        .Filter(fq => fq.Terms(t => t.Field(f => f.BookId).Terms(BookList)))))
         .Aggregations(a => a
         .Terms("group_by_book", ts => ts
         .Field(f => f.BookId)
             .Aggregations(a1 => a1
             .DateHistogram("Date", dat => dat
             .Field(f1 => f1.PubDate)
             .Interval(DateInterval.Day)
             .Format("dd/MM/yyyy")
         )))));

I tried looping the output using following code, but wasn't able to loop any further.

foreach (var agg in searchresponse.Aggregations)
{
    string key = agg.Key;
    IAggregate objIAgg = agg.Value;
}

I can see the values in quickwatch but how do I fetch the values obtained?

Hitesh
  • 3,449
  • 8
  • 39
  • 57

1 Answers1

3

According to the NEST Aggregations Documentation, you need to specify the aggregation you want to access in your results.

There are two ways you can do this, via the Aggregations object as you are doing currently

IAggregate termAggregation = searchresponse.Aggregations["group_by_book"];

Or you can use the Aggs convenience helper to get the right type of aggregation response out of the dictionary based on the key name. In this case it will expose your Terms and related properties from the response.

 TermsAggregate<string> termAgg = searchresponse.Aggs.Terms("group_by_book");

From either of these you should now be able to get to the aggregation values you want. You can examine the different properties available you from these to find the right ones for you.

Additionally if you look at the Term Aggregations Unit tests in the NEST source code you can see some examples of the Aggs property and what you can access.

Russ Cam
  • 124,184
  • 33
  • 204
  • 266
Paige Cook
  • 22,415
  • 3
  • 57
  • 68
  • 1
    In general, I'd recommend using the `Aggs` helper, as it will safely perform the cast from `IAggregate` to the concrete aggregation type for the given aggregation. – Russ Cam Aug 21 '17 at 03:18
  • Thanks a lot Russ for the suggestion, I used the Aggs helper and it was helpful for the cast conversion. – Hitesh Aug 21 '17 at 10:45