嵌套聚合不适用于 AggregationContainer

Nested aggregation not working with AggregationContainer

我在使用嵌套聚合时遇到问题。以下是我如何定义我的聚合和我得到的 json 等价物:

var aggregations = new AggregationDictionary();

var nestedAgg = new AggregationContainer
{
  Nested = new NestedAggregation("some_name1")
  {
    Path = "users",
    Aggregations = new TermsAggregation("some_name2")
    {
       Field = "users.name.keyword",
       Size = 100,
       Order = new List<TermsOrder> { new TermsOrder() { Key = "_term", Order = SortOrder.Descending } }
    }
};

aggregations[aggKey] = nestedAgg;

searchRequest.Aggregations = aggregations;

以上翻译为以下json。它只显示路径,没有聚合定义:

{
  "aggs": {
     "some_name1": {
         "nested": {
            "path": "users"
          }
     }
}

直接使用AggregationDictionaryAggregationContainer有点别扭;你可以这样做

var aggregations = new AggregationDictionary();
var aggKey = "some_name1";

AggregationContainer nestedAgg = new NestedAggregation("some_name1")
{
    Path = "users",
    Aggregations = new TermsAggregation("some_name2")
    {
        Field = "users.name.keyword",
        Size = 100,
        Order = new List<TermsOrder> 
        { 
            new TermsOrder() { Key = "_term", Order = Nest.SortOrder.Descending } 
        }
    }
};

aggregations[aggKey] = nestedAgg;

var searchRequest = new SearchRequest<Test>();

searchRequest.Aggregations = aggregations;

client.Search<Test>(searchRequest);

这里我们使用从 AggregationBase(聚合派生的基础 class)到 AggregationContainer 的隐式转换,将 NestedAggregation 分配给 NestedAggregation 类型的变量=12=]。

This implicit conversion also sets the Aggregations and Meta properties on AggregationContainer, which is why your original attempt doesn't quote work correctly.