首页 > 解决方案 > 无法在 Nest 中选择子聚合

问题描述

我在我的弹性查询中得到了这些结果:

"Results" : {
      "doc_count_error_upper_bound" : 0,
      "sum_other_doc_count" : 0,
      "buckets" : [
        {
          "key" : "73c47133-8656-45e7-9499-14f52df07b70",
          "doc_count" : 1,
          "foo" : {
            "doc_count" : 40,
            "bar" : {
              "doc_count" : 1,
              "customscore" : {
                "value" : 10.496919917864476
              }
            }
          }
        }
      ]

我正在尝试获取以key字段为键、customscore字段为值的匿名对象列表。

无论我尝试什么,我似乎都无法在 Nest 中编写访问该customscore值的代码。显然,我是世界上第一个在 Nest 库中使用嵌套聚合的人。要么,要么文档非常缺乏。我可以轻松到达 Buckets:

response?.Aggregations.Terms("Results").Buckets;

但我不知道如何处理这个对象。Buckets包含几个对象,我假设我可以通过这样做来导航:

bucketObject["foo"]["bar"]["customscore"]

但显然不是。我找到了使用 for 循环的解决方案、具有长 Linq 查询的解决方案,并且所有这些似乎都null为我返回。我错过了什么?

标签: elasticsearchnest

解决方案


假设以下查询,我认为这将与问题中的响应相匹配

var client = new ElasticClient();

var response = client.Search<object>(s => s
    .Index("some_index")
    .Aggregations(a => a
        .Terms("Results", t => t
            .Field("some_field")
            .Aggregations(aa => aa  
                .Filter("foo", f => f
                    .Filter(q => q.MatchAll())
                    .Aggregations(aaa => aaa
                        .Filter("bar", ff => ff
                            .Filter(q => q.MatchAll())
                            .Aggregations(aaaa => aaaa
                                .ValueCount("customscore", vc => vc
                                    .Field("some_other_field")
                                )
                            )
                        )
                    )
                )
            )
        )
    )
);

获取匿名类型的集合将是

var kvs = response.Aggregations.Terms("Results").Buckets
    .Select(b => new 
    { 
        key = b.Key, 
        value = b.Filter("foo").Filter("bar").ValueCount("customscore").Value 
    });

.Aggregations公开将IAggregate响应转换为预期类型的​​方法


推荐阅读