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

时间:2017-01-13 13:12:14

标签: elasticsearch nest

我正在寻找如何使用对象初始化器语法初始化一个没有嵌套聚合的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
              }
         }
 };

请问怎么做?

1 个答案:

答案 0 :(得分:1)

使用Object Initializer语法,您可以将聚合与&&

组合在一起
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);

如果您愿意,可以使用聚合字典使用较长的winded方法

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>中的密钥将是请求中聚合的名称。