本文对应的
Elasticsearch
版本为7.3
概念
bool 过滤器将多个小查询组合成一个大查询,查询语法有如下特点:
- 子查询可以任意顺序出现
- 可以嵌套多个查询,包括bool 查询也可以
- 如果bool查询中没有must条件,should中必须至少满足一条才会返回结果。
bool 过滤器包括四个操作符,must
、must_not
、should
和filter
,这四个都是数组,数组里面是对应的判断条件
- must: 必须匹配。贡献算分
- must_not:过滤子句,必须不能匹配,但不贡献算分
- should: 选择性匹配,至少满足一条。贡献算分
- filter: 过滤子句,必须匹配,但不贡献算分
官方例子
POST _search
{
"query": {
"bool" : {
"must" : [
"term" : { "user" : "kimchy" }
],
"filter": [
"term" : { "tag" : "tech" }
],
"must_not" : [
"range" : {
"age" : { "gte" : 10, "lte" : 20 }
}
],
"should" : [
{ "term" : { "tag" : "wow" } },
{ "term" : { "tag" : "elasticsearch" } }
],
"minimum_should_match" : 1,
"boost" : 1.0
}
}
}
Bool嵌套查询
# 嵌套,实现了 should not 逻辑
POST /products/_search
{
"query": {
"bool": {
"must": [
"term": {
"price": "30"
}
],
"should": [
{
"bool": {
"must_not": [
"term": {
"avaliable": "false"
}
]
}
}
],
"minimum_should_match": 1
}
}
}
SQL和dsl的对照
查询日期在16年10月份且文章标题或内容包含“ES“的文档,用SQL表示为
select * from article where date between '2016-10-01' and '2016-10-31' and (name like '%ES%' or contents like '%ES%')
bool过滤器组合filter
和should
,对应的SQL使用and
来连接
{
"query": {
"bool":{
"filter": [
"range":{
"date":{
"gte":"2016-10-01",
"lte":"2016-10-31"
}
],
"should": [
{"match":{"name":"ES"}},
{"match":{"contents":"ES"}}
]
}
}
}