写在前面
项目中遇到了一个查询问题,原本查询是title=“A” or content=“B”,经需求优化,需要变成(title=“A” or content=“B”) and (state = “C”)。
原始需求
查询title或introduction中满足的字段值
GET forexknow_album_bean/_search
{
"query": {
"bool": {
"should": [
{"match": {
"title": {
"query": "妲",
"boost": 2
}
}},
{"match": {
"introduction": {
"query": "熵"
}
}}
]
}
}
, "size": 20
}
查询结果为null:
{
"took" : 0,
"timed_out" : false,
"_shards" : {
"total" : 5,
"successful" : 5,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : 0,
"max_score" : null,
"hits" : [ ]
}
}
变更需求
查询title或introduction中满足的字段并且state状态等于0
根据对数据库的理解,我就在原先的查询基础上增加了filter过滤,以为能得到想要的结果,没想到啪啪啪打脸。
错误代码:
GET forexknow_album_bean/_search
{
"query": {
"bool": {
"filter": {"term": {
"state": "0"
}},
"should": [
{"match": {
"title": {
"query": "妲",
"boost": 2
}
}},
{"match": {
"introduction": {
"query": "熵"
}
}}
]
}
}
, "size": 20
}
查询结果:
{
"took" : 2,
"timed_out" : false,
"_shards" : {
"total" : 5,
"successful" : 5,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : 105,
"max_score" : 0.0,
"hits" : [
{
"_index" : "forexknow_album_bean",
"_type" : "forexknow_album_bean",
"_id" : "105",
"_score" : 0.0,
"_source" : {
"albumId" : 105,
"title" : "交易谈心社",
"introduction" : "我们希望每一个收听《交易谈心社》的汇友 都能获得一份愉悦和轻松 在这里可以忘记掉 交易时的困扰 生活中的烦恼 用主播可盈的声音温柔地为你分担压力",
"state" : 0
}
},
{
"_index" : "forexknow_album_bean",
"_type" : "forexknow_album_bean",
"_id" : "22",
"_score" : 0.0,
"_source" : {
"albumId" : 22,
"title" : "锄禾日当午汗滴禾下土谁知盘中餐粒粒皆辛苦",
"introduction" : "",
"state" : 0
}
}]
}
}
问题分析
实在是找不到原因,感觉世界观崩塌了,然后看到下面这个话,豁然开朗
其实should在与must或者filter同级时,默认是不需要满足should中的任何条件
解决问题
第一种方法:增加“minimum_should_match”字段,使其必须满足must和filter中的条件,并且必须满足should中的一个条件。
代码如下:
GET forexknow_album_bean/_search
{
"query": {
"bool": {
"filter": {"term": {
"state": "0"
}},
"should": [
{"match": {
"title": {
"query": "妲",
"boost": 2
}
}},
{"match": {
"introduction": {
"query": "熵"
}
}}
],
"minimum_should_match": 1
}
}
, "size": 20
}
Elasticsearch filter与must、should使用问题解析
本文讲述了在项目中遇到的一个Elasticsearch查询问题,原本使用title或content查询,需求优化后需要加上state条件。在尝试在原有查询基础上添加filter过滤后,发现查询结果不符合预期。经过问题分析,了解到should在与must或filter同级时默认不需满足should条件。解决方案是通过设置"minimum_should_match"确保满足特定条件。
1909

被折叠的 条评论
为什么被折叠?



