在 Elasticsearch 中处理可选字段搜索
Handling Optional field search in Elasticsearch
我正在使用 ES 5.5 并且有一个带有 javasript 的查询 dsl API 像这样的请求
client.search({
index: 'demo',
type: 'sample',
body: {
"query": {
"bool": {
"must": [
{
"match": {
"CityName": {
query: req.params.city,
slop: 100
}
}
},
{
"match": {
"StateName": {
query: req.params.state,
slop: 100
}
},
{
"match": {
"Code": {
query: req.params.code,
slop: 100
}
}
}
]
}
}
}
})
当用户给出所有三个参数时,此查询工作正常values.But在我的例子中,这三个参数不是mandatory.Either用户可以给出一个值或多个值和给定的字段must match
具有一个或两个值的 documents.Searching 没有 return 任何东西。
您需要将 must
替换为 should
。参考 boolean query 了解更多详情
client.search({
index: 'demo',
type: 'sample',
body: {
"query": {
"bool": {
"must": [ --> replace this `must` with `should`
{
"match": {
"CityName": {
query: req.params.city,
slop: 100
}
}
},
{
"match": {
"StateName": {
query: req.params.state,
slop: 100
}
},
{
"match": {
"Code": {
query: req.params.code,
slop: 100
}
}
}
]
}
}
}
})
我正在使用 ES 5.5 并且有一个带有 javasript 的查询 dsl API 像这样的请求
client.search({
index: 'demo',
type: 'sample',
body: {
"query": {
"bool": {
"must": [
{
"match": {
"CityName": {
query: req.params.city,
slop: 100
}
}
},
{
"match": {
"StateName": {
query: req.params.state,
slop: 100
}
},
{
"match": {
"Code": {
query: req.params.code,
slop: 100
}
}
}
]
}
}
}
})
当用户给出所有三个参数时,此查询工作正常values.But在我的例子中,这三个参数不是mandatory.Either用户可以给出一个值或多个值和给定的字段must match
具有一个或两个值的 documents.Searching 没有 return 任何东西。
您需要将 must
替换为 should
。参考 boolean query 了解更多详情
client.search({
index: 'demo',
type: 'sample',
body: {
"query": {
"bool": {
"must": [ --> replace this `must` with `should`
{
"match": {
"CityName": {
query: req.params.city,
slop: 100
}
}
},
{
"match": {
"StateName": {
query: req.params.state,
slop: 100
}
},
{
"match": {
"Code": {
query: req.params.code,
slop: 100
}
}
}
]
}
}
}
})