gpt4 book ai didi

java - Elastic Search - 排序 - 在 0 条件下在整数字段之间切换

转载 作者:行者123 更新时间:2023-11-30 03:44:37 25 4
gpt4 key购买 nike

假设我有两个双数据类型字段,分别称为priority1 和priority2。我们需要对priority1进行排序,但是当priority1为0时则选择priority2字段。

示例 -

Document 1 - priority1 : 8.5, priority2 : 9.0
Document 2 - priority1 : 5.5, priority2 : 6.0
Document 3 - priority1 : 0, priority2 : 9.0
Document 4 - priority1 : 8.0, priority2 : 8.5
Document 5 - priority1 : 0, priority2 : 7.5

文件应按顺序排序 -

Document 2  (5.5)
Document 5 (7.5)
Document 4 (8.0)
Document 1 (8.5)
Document 3 (9.0)

最佳答案

您可以使用 custom score 来实现此目的脚本。

以下请求:

POST test/scores/_search
{
"sort":{
"_script":{
"lang":"groovy",
"script" : "doc['priority1'].value == 0 ? doc['priority2'].value : doc['priority1'].value",
"type" : "number",
"order" : "asc"
}
}
}

会给你你想要的订单:

hits": [
{
"_index": "test",
"_type": "scores",
"_id": "7uyu0prrT-SCJFvwSVUI0Q",
"_score": null,
"_source": {
"p1": 5.5,
"p2": 6
},
"sort": [
5.5
]
},
{
"_index": "test",
"_type": "scores",
"_id": "mRjUlMHvQ4-Dj-BKVL1Oyg",
"_score": null,
"_source": {
"p1": 0,
"p2": 7.5
},
"sort": [
7.5
]
},
{
"_index": "test",
"_type": "scores",
"_id": "QKCK2G9GT0y6FzwAvu5p5A",
"_score": null,
"_source": {
"p1": 8,
"p2": 8.5
},
"sort": [
8
]
},
{
"_index": "test",
"_type": "scores",
"_id": "4-kUu3gDSTON9F6bd3ieRw",
"_score": null,
"_source": {
"p1": 8.5,
"p2": 9
},
"sort": [
8.5
]
},
{
"_index": "test",
"_type": "scores",
"_id": "KOqf6bhrTK2JioRFEppcjw",
"_score": null,
"_source": {
"p1": 0,
"p2": 9
},
"sort": [
9
]
}
]

直接使用 function_score 查询(此处为 documentation)并在查询中重复使用相同的脚本可以获得更好的性能。

关于java - Elastic Search - 排序 - 在 0 条件下在整数字段之间切换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26054554/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com