ElasticSearch过滤器聚合

3
我需要返回每个父元素的子元素数量。这是我的解决方案:
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获取相同的数据。

1个回答

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

希望它能对你有所帮助。

谢谢,这非常有帮助。 - Julia

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接