【问题标题】:ElasticSearch Filter aggregationElasticSearch 过滤器聚合
【发布时间】:2015-09-17 05:51:15
【问题描述】:

我需要返回每个父母的孩子人数。这是我的解决方案:

foreach (var person in someList)
{
  var countingFields = _elasticsearchClient.Search<SomeModel>(esModel=> esModel
                            .Aggregations(aggregation => aggregation
                                .Filter("Parents", filter => filter
                                    .Filter(innerFilter => innerFilter
                                        .Term(field => field.ParentId, person.Id))
                                    .Aggregations(innerAggregation => innerAggregation
                                        .ValueCount("Counting", count => count
                                            .Field(field => field.ParentId))))));
}

我需要帮助来改进这一点,我想通过一个与 ElasticSearch 的连接来获得相同的数据。

【问题讨论】:

    标签: c# elasticsearch filter aggregation nest


    【解决方案1】:

    您可以将ValueCount 替换为terms 聚合。 所以你会得到如下结果:

    ParentId Count
    1        4
    2        3
    

    我的测试数据集:

    client.Index(new SomeModel {Id = 1, ParentId = 1});
    client.Index(new SomeModel {Id = 2, ParentId = 2});
    client.Index(new SomeModel {Id = 3, ParentId = 3});
    client.Index(new SomeModel {Id = 4, ParentId = 1});
    

    NEST 术语聚合语法:

    var someList = new List<int>{1,2,3,4};
    
    var countingFields = client.Search<SomeModel>(esModel => esModel
        .Aggregations(aggregation => aggregation
            .Filter("Parents", filter => filter
                .Filter(innerFilter => innerFilter
                    .Terms(field => field.ParentId, someList))
                .Aggregations(innerAggregation => innerAggregation
                    .Terms("Counting", count => count
                        .Field(field => field.ParentId))))));
    

    回复:

    "aggregations": {
       "Parents": {
          "doc_count": 4,
          "Counting": {
             "doc_count_error_upper_bound": 0,
             "sum_other_doc_count": 0,
             "buckets": [
                {
                   "key": 1,
                   "doc_count": 2
                },
                {
                   "key": 2,
                   "doc_count": 1
                },
                {
                   "key": 3,
                   "doc_count": 1
                }
             ]
          }
       }
    }
    

    希望对你有帮助。

    【讨论】:

    • 谢谢,很有帮助。
    猜你喜欢
    • 2014-02-02
    • 1970-01-01
    • 1970-01-01
    • 2014-12-11
    • 2020-02-01
    • 2015-12-30
    • 2016-03-14
    • 2016-05-30
    • 1970-01-01
    相关资源
    最近更新 更多