如何在使用脚本对 Elasticsearch 中的结果进行排序时获取 _score 而不是 null

How to get _score instead of null while using Script to sort Results in Elasticsearch

在使用脚本对查询结果进行排序时,为什么 Elasticsearch 给出的是 null 而不是实际分数。

我正在使用这个简单的脚本进行测试。

PUT _scripts/simple_sorting
{
  "script" :{
    "lang": "painless",
    "source": """
      return  Math.random();
    """
  }
}

查询是

GET some_index/_search
{
  "explain": true, 
    "stored_fields": [
      "_source"
      ], 
    "sort": {
      "_script":{
        "type" : "number",
        "script" : {
          "id": "simple_sorting"
        },
        "order" : "desc"

      }
    },
    "query" : {
      "bool": {
        "should": [
          {
            "match": {
              "tm_applied_for": {
                "query": "bisire"
              }
            }
          }
        ]
      }
    }
}

查询给了我这样的结果。

{
  "took" : 2,
  "timed_out" : false,
  "_shards" : {
    "total" : 1,
    "successful" : 1,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : {
      "value" : 20,
      "relation" : "eq"
    },
    "max_score" : null,
    "hits" : [
      {
        "_shard" : "[some_index][0]",
        "_node" : "UIMgEAZNRzmIpRGyQt232g",
        "_index" : "some_index",
        "_type" : "_doc",
        "_id" : "1171229",
        "_score" : null,
        "_source" : {
          "status" : "Registered",
          "proprietor_name
.
.
.
.
          "@timestamp" : "2020-03-27T20:05:25.753Z",
          "tm_applied_for_anan" : "BISLERI"
        },
        "sort" : [
          0.28768208622932434
        ],

您可以看到 max_score_score 值为空。但是它在 sort 数组中给出了一个值,elasticsearch 根据该值对文档进行了排序。

我希望在我使用脚本排序之前 Elasticsearch 给 Query 的原始分数被返回而不是 null。

另外,当我按如下方式更改脚本 simple_sorting 时。我在 sort 数组(比如 0.234...)中得到了一些值,它不等于它之前返回的值(比如 12.1234...) 当我没有使用脚本排序时。

PUT _scripts/simple_sorting
{
  "script" :{
    "lang": "painless",
    "source": """
      return  _score;
    """
  }
}

为什么_score 值两次都不一样?

当 Elasticsearch Documentation 明确表示我可以在使用脚本排序时访问 _score

当我使用脚本进行排序时,我期望发生的事情就是这样。

1) max_score_score 保持 Elasticsearch 给出的原样,而不是变为空值。

2) 根据 Math.random() 值进行排序。

这是 elasticsearch 的默认行为,因为您使用自己的逻辑对结果进行排序,因此它忽略了分数。为了仍然获得分数,请将 track_scores 参数设置为 true。这将为您提供 elasticsearch 计算的相关性分数。

GET some_index/_search
{
  "explain": true,
  "stored_fields": [
    "_source"
  ],
  "sort": {
    "_script": {
      "type": "number",
      "script": {
        "id": "simple_sorting"
      },
      "order": "desc"
    }
  },
  "query": {
    "bool": {
      "should": [
        {
          "match": {
            "tm_applied_for": {
              "query": "bisire"
            }
          }
        }
      ]
    }
  },
  "track_scores": true
}