elasticsearch nest:使用对象初始化语法创建具有多个聚合的 SearchRequest

elasticsearch nest: create SearchRequest with multi Aggregations using the object initializer syntax

我正在寻找如何使用对象初始化语法来初始化具有多个无嵌套聚合的 SearchRequest 对象。

如果使用 lambda 表达式助手将请求作为参数传递给 ElasticClient.Search(),它将像下面这样写:

   var response = Client.Search<person>(s => s.Aggregations(a => 
            a.Terms("bucketAge", t => t.Field("age").Size(50))
             .Terms("bucketCity", t => t.Field("city").Size(50))));

矛盾的是​​我发现我如何用嵌套的 Agg 编写 Agg

 var searchRequest = new SearchRequest<person>
        {
            Size = 0,
            Aggregations =
           new TermsAggregation("bucketAge")
           {
               Field = "age",
               Size = 50,
               Aggregations = new TermsAggregation("bucketcity")
               {
                   Field = "city",
                   Size = 50
             }
           }
        };

但是我无法使用 2 个 aggs 在同一级别初始化 SearchRequest 类似这样的东西:

var searchRequest = new SearchRequest<person>
{
        Size = 0,
        Aggregations =
        {
              new TermsAggregation("bucketAge")
              {
                  Field = "age",
                  Size = 50
              },
              new TermsAggregation("bucketcity")
              {
                  Field = "city",
                  Size = 50
              }
         }
 };

请问如何操作?

使用对象初始化器语法,您可以将聚合与 &&

结合使用
var searchRequest = new SearchRequest<person>
{
    Size = 0,
    Aggregations =
      new TermsAggregation("bucketAge")
      {
          Field = "age",
          Size = 50
      } &&
      new TermsAggregation("bucketcity")
      {
          Field = "city",
          Size = 50
      }

};

var searchResponse = client.Search<person>(searchRequest);

如果您愿意,可以使用聚合字典使用更长的缠绕方法

var aggregations = new Dictionary<string, AggregationContainer>
{
    { "bucketAge", new TermsAggregation("bucketAge")
      {
          Field = "age",
          Size = 50
      }
    },
    { "bucketcity", new TermsAggregation("bucketcity")
      {
          Field = "city",
          Size = 50
      }
    },
};

var searchRequest = new SearchRequest<person>
{
    Size = 0,
    Aggregations = new AggregationDictionary(aggregations)
};

var searchResponse = client.Search<person>(searchRequest);

请注意,Dictionary<string, AggregationContainer> 中的键将是请求中聚合的名称。