一、布尔查询
ElasticSearch 支持的布尔逻辑类型包括有以下几种:
must
:文档必须符合其中所有的查询条件,包含多个条件时类似于SQL中的AND
。
should
:文档必须符合其中任意一个及以上查询条件(可由minimum_should_match
指定需要满足的条件数量),包含多个条件时类似于SQL中的OR
。
must_not
:文档必须不符合其中所有的查询条件,类似于SQL中的NOT
,且采用过滤器执行而不需要计算文档的得分,所以返回的结果的分值都为0
。
filter
:效果与使用must
相同。但 filter 查询不参与查询结果的分值计算,它返回的文档的分值始终为 0。filter 的使用场景适合于过滤不需要的文档,但又不影响最终计算的得分。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| { "query": { "bool": { "must": [ { "term": { "age": 20 } }, { "term": { "gender": "male" } } ], "must_not": { "term": { "gender": "hello" } } } } }
|
如上,当查询运行后,将返回 age 的值为 20 且 gender 的值为 “male” ,不为 “hello” 的文档。
1. must 查询
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| // 1. 当 must 查询只包括一个查询条件时,可在 DSL 中使用 json 对象的形式表示 { "query": { "bool": { "must": { "term": { "age": 20 } } } } } // 2. must 查询可以同时指定多个查询条件,在 DSL 中以数组的形式表示 { "query": { "bool": { "must": [ { "term": { "age": 20 } }, { "term": { "gender": "male" } } ] } } } // 3. filter 查询不参与查询结果的分值计算,用法和 must 查询一致
|
2. should 查询
可以使用 minimum_should_match
参数指定至少满足几个条件
1 2 3 4 5 6 7 8 9 10 11 12
| { "query": { "bool": { "should": [ { "term": { "age": 20 } }, { "term": { "gender": "male" } }, { "term": { "height": 170 } }, ], "minimum_should_match": 2 } } }
|
在同一个bool
语句中若不存在must
或filter
时,minimum_should_match
默认的值为1,即至少要满足其中一个条件;但若有其它must
或filter
存在时,minimum_should_match
默认值为0。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| { "query": { "bool": { "must": { "term": { "age": 20 }, }, "should": { "term": { "status": "active" } } } } }
|
如上查询,所有返回的文档 age 值必定为 20,但其中可能包括有 status 不为 active 的文档。
二、布尔组合查询
需要注意:布尔查询必须包含在 bool 查询语句中,所以在嵌套查询中必须在内部再次使用 bool 查询语句
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| { "query": { "must": [ { "bool": { "should": [ { "term": { "age": 20 } }, { "term": { "age": 25 } } ] } }, { "range": { "level": { "gte": 3 } } } ] } } // 就类似于:SELECT * FROM xxx WHERE (age = 20 OR age = 25) AND level >= 3;
|