记录下今天编码时遇到的问题,在filter和should同级并用的查询下,should子句并没有生效,只有filter子句生效。
例如以下dsl
{
"query": {
"bool": {
"filter": [
{
"term": {
"status": 3
}
}
],
"should": [
{
"bool": {
"filter": [
{
"bool": {
"must_not": {
"exists": {
"field": "last_recheck_time"
}
}
}
},
{
"range": {
"qc_end_time": {
"lte": 1713769642
}
}
}
]
}
},
{
"range": {
"last_recheck_time": {
"lte": 1713769642
}
}
}
]
}
}
}
这是因为在filter/must和should并列使用时,当filter/must满足时,should子句默认会被忽略,如果需要filter/must满足的同时,should中的条件也要满足,有两种方法可以修改我们原本的查询。
方法1 使用minimum_should_match
在should同级增加参数minimum_should_match,修改后的dsl如下
{
"query": {
"bool": {
"filter": [
{
"term": {
"status": 3
}
}
],
"minimum_should_match":1,
"should": [
{
"bool": {
"filter": [
{
"bool": {
"must_not": {
"exists": {
"field": "last_recheck_time"
}
}
}
},
{
"range": {
"qc_end_time": {
"lte": 1713769642
}
}
}
]
}
},
{
"range": {
"last_recheck_time": {
"lte": 1713769642
}
}
}
]
}
}
}
方法2 合并filter和should子句
可将should子句和filter子句合并,将should子句作为filter子句内的一部分,达到想要的查询效果
{
"query": {
"bool": {
"filter": [
{
"term": {
"status": 0
}
},
{
"bool": {
"should": [
{
"bool": {
"filter": [
{
"bool": {
"must_not": {
"exists": {
"field": "last_recheck_time"
}
}
}
},
{
"range": {
"qc_end_time": {
"lte": 0
}
}
}
]
}
}
,{
"range": {
"last_recheck_time": {
"lte": 0
}
}
}
]
}
}
]
}
}
}
参考: