【问题标题】:Elasticsearch multiple aggregations from array来自数组的 Elasticsearch 多个聚合
【发布时间】:2017-02-16 10:30:45
【问题描述】:

如何在一个查询中动态组合多个聚合?

我知道要“硬编码”:

request.Aggregations = new TermsAggregation("agg_field1") {
    Field = "field1"
}
&& new TermsAggregation("agg_field2") {
    Field = "field2"
};

但由于我使用包含字段的数组,因此我需要类似以下内容。但我收到编译器错误,因为运算符 '&=' 无法组合 'AggregationDictionary' 和 'TermsAggregation':

string[] Fields = new[]{ "field1", "field2" }
foreach (string sField in Fields)
{
    request.Aggregations &= new TermsAggregation("agg_" + sField)
    {
        Field = sField
    };
}

我有“产品”、“品牌”、“型号”等字段的文章数据。 对于这个字段,我想通过聚合获得每个不同的值。它用于显示三个组合框以及每个字段的可能值。

【问题讨论】:

    标签: c# .net elasticsearch nest


    【解决方案1】:

    您可以通过几种不同的方式来构建聚合集合。最接近你想要做的事情是

    var request = new SearchRequest<object>();
    
    string[] Fields = new[] { "field1", "field2" };
    AggregationBase aggregations = null;  
    foreach (string sField in Fields)
    {
        var termsAggregation = new TermsAggregation("agg_" + sField)
        {
            Field = sField
        };
    
        if (aggregations == null)
        {
            aggregations = termsAggregation;
        }
        else
        {
            aggregations &= termsAggregation;
        }
    }
    
    request.Aggregations = aggregations;
    
    client.Search<object>(request);
    

    构建以下查询

    {
      "aggs": {
        "agg_field1": {
          "terms": {
            "field": "field1"
          }
        },
        "agg_field2": {
          "terms": {
            "field": "field2"
          }
        }
      }
    }
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-10
    • 1970-01-01
    • 2017-11-27
    • 1970-01-01
    • 1970-01-01
    • 2014-10-25
    • 2021-07-26
    相关资源
    最近更新 更多