我在 ElastiSearch 中有以下資料結構。
[{
"name": "Kapil",
"age": 32,
"hobbies": ["Cricket", "Football", "Swimming"]
},
{
"name": "John",
"age": 33,
"hobbies": ["Baseball", "Football", "Swimming"]
},
{
"name": "Vick",
"age": 30,
"hobbies": ["Baseball", "Karate", "Swimming"]
}]
我想按以下順序從資料中獲取所有記錄:
- 獲取所有有
Football興趣的用戶并按年齡對他們進行排序。 - 獲取所有其他用戶按年齡降序排序。
因此,按照 John、Kapil 和 Vick 的順序期待結果。
我使用下面的查詢來獲取 #1 的結果。
{
"size": 500,
"query": {
"bool": {
"must": [
{
"match_phrase": {
"hobbies.keyword": "Football"
}
}
]
}
},
"sort": [
{
"age": {
"order": "desc"
}
}
]
}
并在下面用于第 2 點
{
"size": 500,
"query": {
"bool": {
"must_not": [
{
"match_phrase": {
"hobbies.keyword": "Football"
}
}
]
}
},
"sort": [
{
"age": {
"order": "desc"
}
}
]
}
有了上面,我無法維護分頁邏輯。它還要求我分別執行兩個查詢。有人可以幫助如何實作這一目標嗎?
uj5u.com熱心網友回復:
試試這個:
{
"query": {
"bool": {
"must": {
"match_all": {} <-- retrieve all docs
},
"should": { <-- give higher score to docs that match this clause
"match_phrase": {
"hobbies.keyword": "Football"
}
}
}
},
"sort": [
"_score", <-- sort by doc score first
{
"age": { <-- when score is equal then sort by age
"order": "desc"
}
}
]
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/372569.html
