在使用脚本对查询结果进行排序时,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 时。当我不使用脚本进行排序时,我在排序数组(例如 0.234 ... )中得到了一些值,该值不等于它先前返回的值(例如 12.1234 ... )。
PUT _scripts/simple_sorting
{
"script" :{
"lang": "painless",
"source": """
return _score;
"""
}
}
为什么_score值两次都不相同?
当Elasticsearch Documentation明确表示我可以使用脚本进行排序时访问 _score 。
我期望使用Script进行排序时会发生这种情况。
1) max_score 和 _score 保持与Elasticsearch给出的一样,而不是变为null。
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
}