Elasticsearch来自数组的多个聚合

时间:2017-02-15 17:55:32

标签: c# .net elasticsearch nest

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

我知道这样做"硬编码":

didSelectContactProperty

但是因为我使用包含字段的数组,所以需要类似下面的内容。但我收到了编译错误,因为' AggregationDictionary'和' TermsAggregation'不能由运营商组合'& =':

contactPicker.predicateForEnablingContact = [NSPredicate predicateWithFormat:@"phoneNumbers.@count > 0"];
contactPicker.predicateForSelectionOfContact = [NSPredicate predicateWithFormat:@"phoneNumbers.@count == 1"];
contactPicker.predicateForSelectionOfProperty = [NSPredicate predicateWithFormat:@"key == 'phoneNumbers'"];

我的文章数据包含" product","品牌"," modell"等字段。 对于这个字段,我想通过聚合获得每个不同的值。它用于显示三个组合框,其中包含每个字段的可能值。

1 个答案:

答案 0 :(得分:3)

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

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"
      }
    }
  }
}