ES bool查询

发布时间 2023-09-18 00:05:57作者: nanxinyi

一、bool查询包含四种操作

在Elasticsearch中,可以使用bool查询来实现多条件查询。bool查询是一种组合查询,可以通过组合多个查询条件来实现更复杂的查询需求。bool查询包含以下子查询:

1. must查询:表示必须满足的查询条件,相当于逻辑运算中的“与”。如果某条文档满足所有的must查询条件,才会被返回。

2. should查询:表示可选的查询条件,相当于逻辑运算中的“或”。如果某条文档满足其中任意一个should查询条件,则会被返回。

3. must_not查询:表示必须不满足的查询条件,相当于逻辑运算中的“非”。如果某条文档满足任意一个must_not查询条件,则不会被返回。

以下是一个bool多条件查询的示例:


{
  "query": {
    "bool": {
      "must": [
        { "match": { "title": "Elasticsearch" }},
        { "match": { "author": "John" }}
      ],
      "should": [
        { "match": { "category": "Technology" } },
        { "match": { "category": "Science" }}
      ],
      "must_not": [
        { "match": { "status": "Archived" }}
      ]
    }
  }
}

上面的查询条件表示查询标题中包含“Elasticsearch”并且作者为“John”,或者分类为“Technology”或“Science”,但不包括状态为“Archived”的文档。

二、功能

1.must 对应mysql的 and a=

2.must not 对应mysql的 and a!=

3.filter 对应mysql的 and a=

4.should 对应mysql的 or a=

 

三、must和filter比较

1.must算分,filter不算分

2.filter效率比must高

 

四、filter效率高的原理

1.query context:文档更加匹配查询条件,分数越高越匹配

2.filter context:文档是否匹配查询条件,并且ES会缓存查询结果