编写 NEST 查询以按分数对聚合桶进行排序

Writing a NEST query to sort aggregation buckets by score

我想要的是为每个 unitId(这是我文档中的一个字段)创建一个聚合桶。我希望每个桶都按该桶中的最高分数排序。我编写了以下查询来执行我想要的操作:

 "aggs": {
    "UnitAggregationBucket": {
      "terms": {
        "field": "unitId",
        "size": 10,
        "order": {
          "max_score": "desc"
        }
      },
      "aggs": {
        "max_score": {
          "max": {
            "script": "_score"
          }
        }
      }
    }

我正在使用脚本在子聚合中查找每个存储桶的最高分数。我不知道如何使用 NEST 编写上述查询?

更新:

这是我从Elastic Community得到的答案:

With 6.x, this would be something like:

var client = new ElasticClient();

var searchResponse = client.Search<object>(s => s
    .Aggregations(a => a
          .Terms("UnitAggregationBucket", t => t
              .Field("unitId")
          .Size(10)
          .Order(o => o
              .Descending("maximum_score")
          )           
            .Aggregations(aa => aa
              .Max("maximum_score", m => m
                  .Script("_score")
              )
          )
      )
  ) 
);

var termsAgg = searchResponse.Aggregations.Terms("UnitAggregationBucket");

foreach(var bucket in termsAgg.Buckets)
{     
    // do something with buckets  
    var maxScore = bucket.Max("maximum_score").Value; 
}

Note that you can't use max_score for the name of the aggregation as it's a reserved keyword name in the client, which the client uses in its heuristics based aggregation response JSON deserialization method.


原答案

我设法编写了以下 NEST 查询:

var unitAggregations = new TermsAggregation("UnitAggregationBucket")
{
    Size 10,
    Field = Field<MyDocument>(p => p.UnitId),
    Order = new List<TermsOrder>
    {
        new TermsOrder()
        {
            Key = "max_score_in_bucket",
            Order = SortOrder.Descending
        }
    },
    Aggregations = new MaxAggregation("max_score_in_bucket", string.Empty)
    {
        Script = new InlineScript("_score")
    }
};

产生以下 json:

"aggs": {
    "UnitAggregationBucket": {
      "aggs": {
        "max_score_in_bucket": {
          "max": {
            "script": {
              "source": "_score"
            }
          }
        }
      },
      "terms": {
        "field": "unitId",
        "order": [
          {
            "max_score_in_bucket": "desc"
          }
        ],
        "size": 10
      }
    }
  }

这不是我想要的确切 json,但它符合我的要求。


注意:max_score 是 Elasticsearch 中的保留关键字,所以我不得不使用不同的名称:max_score_in_bucket