elasticsearch中 同时使用should和must 导致只有must生效 解决方案

使用ES查询语句的时候 会遇到嵌套多条件查询情况
  • title或者content包含xx(should)

  • type必须是1(must)

  • enabled必须是1(must_not)

只使用SHOULD查询


GET _search
{
  "query": {
    "bool": {
      "should": [
        {
          "match_phrase": {
            "title": "疫情期间"
          }
        },
        {
          "match_phrase": {
            "content": "疫情期间"
          }
        }
      ],
      "must_not": [
        {
          "match": {
            "enabled": 0
          }
        }
      ]
    }
  },
  "highlight": {
    "pre_tags": [
      "<font color='red'>"
    ],
    "post_tags": [
      "</font>"
    ],
    "fields": {
      "title": {},
      "content": {}
    }
  }
}

鼎云博客

如果直接使用查询语句 会发现 查询出的结果 只满足MUST条件 SHOULD失效了
GET _search
{
  "query": {
    "bool": {
      "should": [
        {
          "match_phrase": {
            "title": "疫情期间"
          }
        },
        {
          "match_phrase": {
            "content": "疫情期间"
          }
        }
      ],
      "must": [
        {"match": {
          "type": "1"
        }}
      ], 
      "must_not": [
        {
          "match": {
            "enabled": 0
          }
        }
      ]
    }
  },
  "highlight": {
    "pre_tags": [
      "<font color='red'>"
    ],
    "post_tags": [
      "</font>"
    ],
    "fields": {
      "title": {},
      "content": {}
    }
  }
}

鼎云博客


最终结果

使用多个must嵌套查询 将should组成的bool查询包含在其中一个must查询中

鼎云博客

GET _search
{
  "query": {
    "bool": {
      "must": [
        {
          "bool": {
            "should": [
              {
                "match_phrase": {
                  "title": "疫情期间"
                }
              },
              {
                "match_phrase": {
                  "content": "疫情期间"
                }
              }
            ]
          }
        },
        {
          "match": {
            "type": "1"
          }
        }
      ],
      "must_not": [
        {
          "match": {
            "enabled": 0
          }
        }
      ]
    }
  },
  "highlight": {
    "pre_tags": [
      "<font color='red'>"
    ],
    "post_tags": [
      "</font>"
    ],
    "fields": {
      "title": {},
      "content": {}
    }
  }
}



鼎云博客

//PHP代码实现,$this->must是完整的must条件

$keys = ['name', 'scope', 'oper_name', 'address', 'employees', 'partners', 'products'];
$should = [];
foreach ($keys as $key) {
    $should[] = ['match_phrase' => [$key => $this->$attribute]];
}
unset($key);
if(!empty($should)){
    $this->must[] = [
        'bool' => [
            'should' => $should,
        ],
    ];
}


鼎云博客
  • 最新评论
  • 总共0条评论