我有這個匹配兩個條件的彈性搜索功能。但是現在“型別”是可選的,如果未設定型別并且設定了型別,我希望回傳所有 cookie,我希望得到與下面查詢相同的結果。型別是一個列舉(如果重要的話)。
export const searchCookies: HttpFunction = enrichCloudFunction(async (req, res) => {
const {
query: { type, cookies, from, size },
} = validateCookieQuery(req)
const {
hits: { hits },
} = await elastic.search<ExtendedStuff>({
from: from || 0,
index: cookieIndex({ prefix: config.prefix }),
query: {
bool: {
must: [
{
match: { 'cookie.id': cookie },
},
{
match: { type },
},
],
},
},
size: size || 20,
})
res.json(hits.map((x) => x._source))
})
這可能是一件非常微不足道的事情,但這是我第一次使用彈性搜索,我非常困惑。
uj5u.com熱心網友回復:
我會檢查 Elastic 檔案以獲取可用選項,但您也可以按照以下方式提出條件陳述句:
export const searchCookies = enrichCloudFunction(async (req, res) => {
const { query: { type, cookies, from, size } } = validateCookieQuery(req)
const boolOptions = {
must: [ { match: { 'cookie.id': cookie } } ]
}
if ( type ){
boolOptions.must.push({ match: { type }})
}
const { hits: { hits } } = await elastic.search<ExtendedStuff>({
from: from || 0,
index: cookieIndex({ prefix: config.prefix }),
query: { bool: boolOptions },
size: size || 20,
})
res.json(hits.map((x) => x._source))
})
uj5u.com熱心網友回復:
您可以使用should 子句,如果滿足任何子句,它將回傳一個檔案。我在 should 中使用了 2 個查詢
- 必須不存在 - 這將回傳沒有設定欄位的檔案
- match - 這將回傳具有匹配型別值的檔案
此外,您可以使用 must/filter - 回傳具有匹配 cookie id 并滿足任何 should 子句的檔案。
如果您只是過濾,請使用過濾器。過濾器不計算分數,因此速度更快。
{
"query": {
"bool": {
"minimum_should_match": 1,
"should": [
{
"bool": {
"must_not": {
"exists": {
"field": "title"
}
}
}
},
{
"match": { type }
}
],
"must": [
{
"match": { 'cookie.id': cookie }
}
]
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/523565.html
