彈性搜索版本:
我們想構建一個如下所示的查詢
......
......
bool: {
must: [
match : {
myfield.myfield2.keyword : {
query: "myvalue"
}
}
]
}
......
......
我們如何以一種方式修改上述內容:
- "myvalue" 是一個空字串:我們希望 elasticsearch 忽略它而不是搜索空字串
- “我的價值”不為空。我們應該得到完全匹配
uj5u.com熱心網友回復:
您應該在構建查詢時在應用程式代碼中執行此檢查,如果 myvalue為空或為 null,則不添加查詢。
如果由于任何原因無法做到這一點,那么在 Elasticsearch 中有一種方法可以使用使用Mustache 模板語言構建的搜索模板來執行此操作。
基本上,您的查詢看起來像這樣,match只有在myvalue具有非空、非假、非空值時才添加查詢:
POST _scripts/my-query
{
"script": {
"lang": "mustache",
"source": """
{
"query": {
"bool": {
"must": [
{{#myvalue}}
{
"match" : {
"myfield.myfield2.keyword" : {
"query": "myvalue"
}
}
}
{{/myvalue}}
]
}
}
}
"""
}
}
如果您使用 null、false、空值呼叫此搜索模板,則match不會添加查詢
POST _render/template
{
"id": "my-query",
"params": {
"myvalue": ""
}
}
=>
{
"query" : {
"bool" : {
"must" : [ ]
}
}
}
而如果您使用非空、非假、非空值呼叫它,match則會添加查詢:
POST _render/template
{
"id": "my-query",
"params": {
"myvalue": "test"
}
}
=>
{
"query" : {
"bool" : {
"must" : [
{
"match" : {
"myfield.myfield2.keyword" : {
"query" : "myvalue"
}
}
}
]
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/366901.html
標籤:弹性搜索
上一篇:bool查詢是否存在執行順序?
下一篇:彈性搜索不回傳最近30分鐘的資料
