我想使用弹性在PHP处理从我的网站的搜索请求。例如,我有搜索参数
nameageheightweight。但是,不应该总是搜索所有参数。
因此,可能只有(name和age)有值,而(height和weight)没有。
是否有一种方法可以使用灵活/更改的输入值构建一个查询?
当没有搜索值(height和weight)时,下面的查询将无法工作。
{
"query": {
"bool": {
"should": [
{ "match": { "name.keyword": "Anna" } },
{ "match": { "age": "30" } },
{ "match": { "height": "180" } },
{ "match": { "weight": "70" } }
]
}
}
}发布于 2022-07-26 11:21:47
搜索模板到救援:
POST _scripts/my-search-template
{
"script": {
"lang": "mustache",
"source": """
{
"query": {
"bool": {
"should": [
{{#name}}
{ "match": { "name.keyword": "{{name}}" } },
{{/name}}
{{#age}}
{ "match": { "age": "{{age}}" } },
{{/age}}
{{#height}}
{ "match": { "height": "{{height}}" } },
{{/height}}
{{#weight}}
{ "match": { "weight": "{{weight}}" } },
{{/weight}}
{ "match_none": { } }
]
}
}
}
"""
}
}请注意,由于您不知道有多少条件,最后一个条件始终是假的,只有在那里确保JSON是有效的(即最后一个逗号不停留在悬空中)。
然后,您可以像这样运行查询:
POST my-index/_search/template
{
"id": "my-search-template",
"params": {
"name": "Anna",
"age": 30
}
}发布于 2022-07-26 10:49:16
您需要在构造Elasticsearch查询的应用程序中处理,并且在应用程序中很容易处理,因为您知道从UI获得的所有搜索参数值(如果它们不是空的,而不是仅包括Elasticsearch查询中的那些字段)。
弹性搜索不支持查询.中类似if...else的条件
发布于 2022-07-26 12:16:01
Tldr;
它们是在Elasticsearch中解决问题的多种方法。
你可以和minimum_should_match一起玩
你可以使用带有条件的模板查询。
您还可以执行更复杂的bool查询,它枚举匹配的可能性。
您也可以使用您想要看到的编写逻辑的脚本。
最小值应匹配
POST /_bulk
{"index":{"_index":"73121817"}}
{"name": "ana", "age": 1, "height": 180, "weight": 70}
{"index":{"_index":"73121817"}}
{"name": "jack", "height": 180, "weight": 70}
{"index":{"_index":"73121817"}}
{"name": "emma", "age": 1, "weight": 70}
{"index":{"_index":"73121817"}}
{"name": "william", "age": 1, "height": 180}
{"index":{"_index":"73121817"}}
{"name": "jenny", "weight": 70}
{"index":{"_index":"73121817"}}
{"name": "marco", "age": 1}
{"index":{"_index":"73121817"}}
{"name": "giulia", "height": 180}
{"index":{"_index":"73121817"}}
{"name": "paul"}
GET 73121817/_search
{
"query": {
"bool": {
"should": [
{ "match": { "name.keyword": "Anna" } },
{ "match": { "age": "30" } },
{ "match": { "height": "180" } },
{ "match": { "weight": "70" } }
],
"minimum_should_match": 2
}
}
}将最小应匹配设置为2,只返回2个文档( ana和jack )。
模板查询
你也可以请参阅医生
复杂查询
参考链接后面的so帖子
脚本查询
GET 73121817/_search
{
"query": {
"bool": {
"filter": {
"script": {
"script": """
return (!doc["name.keyword"].empty && !doc["age"].empty);
"""
}
}
}
}
}https://stackoverflow.com/questions/73121817
复制相似问题