在弹性搜索嵌套中循环聚合c#

时间:2017-08-17 06:17:54

标签: c# elasticsearch nest elasticsearch-5 elasticsearch-net

我希望在Elastic:

中实现以下SQL查询的等价物
select BookId, PubDate, count(1)
from BookMessages
where BookId in (1,2)
group by BookId, PubDate

因此我用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")
         )))));

我尝试使用以下代码循环输出,但无法进一步循环。

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

我可以在quickwatch中看到值,但是如何获取获得的值?

1 个答案:

答案 0 :(得分:2)

根据NEST Aggregations Documentation,您需要在结果中指定要访问的汇总。

通过Aggregations对象,您可以通过两种方式执行此操作

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

或者您可以使用Aggs便利助手根据键名从字典中获取正确类型的聚合响应。在这种情况下,它将从响应中公开您的条款和相关属性。

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

您可以从其中任何一个获得所需的聚合值。您可以检查这些可用的不同属性,以便为您找到合适的属性。

此外,如果您查看Term Aggregations Unit tests in the NEST source code,您可以看到Aggs属性的一些示例以及您可以访问的内容。

相关问题