Скажем, у меня есть два поля двойного типа данных, называемые priority1 и priority2. Нам нужно отсортировать приоритет1, но когда приоритет1 равен 0, выберите поле приоритета2.
Пример -
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)
Вы можете достичь этого, используя собственный скрипт оценки.
Следующий запрос:
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
запрос (документация здесь) и повторное использование и тот же сценарий в запросе.