布尔查询可以组合前边的一些查询,比如组合filter和must/must_not等等
它的目的就是提高性能,比如先通过filter过滤一些数据之后,然后再计算评分,这样节省一些评分时间
POST test_goods/_doc
{
"name": "apple watch",
"price": 6999,
"date": "2023-06-27"
}
POST test_goods/_doc
{
"name": "apple ring",
"price": 999,
"date": "2023-06-27"
}
POST test_goods/_doc
{
"name": "apple phone",
"price": 7999,
"date": "2023-06-27"
}
POST test_goods/_doc
{
"name": "apple",
"price": 9999,
"date": "2023-06-27"
}
GET test_goods/_search
GET test_goods/_search
{
"query": {
"bool": {
"filter": [
{
"range": {
"price": {
"gte": 0,
"lte": 99999
}
}
}
],
"must": [
{
"match": {
"name.keyword": "apple"
}
}
]
}
}
}
must
GET test_mapping_manual1/_search
{
"query": {
"bool": {
"must": [
// 可以设置多个查询条件, 所有条件必须满足
{},{}
]
}
}
}
"must": [
// 可以设置多个查询条件, 所有条件必须满足
should
must:必须满足子句(查询)必须出现在匹配的文档中,并将有助于得分。
filter:过滤器 不计算相关度分数,cache☆子句(查询)必须出现在匹配的文档中。但是不像 must查询的分数将被忽略。Filter子句在filter上下文中执行,这意味着计分被忽略,并且子句被考虑用于缓存。
should:可能满足 or子句(查询)应出现在匹配的文档中。
should:参数指定should返回的文档必须匹配的子句的数量或百分比。可以写多个条件,这些条件中它要求最低要满足几个条件才算命中, 默认[如果bool查询包含至少一个 should 子句,而没有 must 或 filter 子句,则默认值为 1。否则,默认值为0],可以配置.minimum_should_match:
minimum_should_match
可以接受以下几种不同的取值:
- 固定数量值:可以指定一个具体的数字,例如
minimum_should_match: 2
,表示至少需要两个should
条件匹配。- 百分比值:可以指定一个百分比值,例如
minimum_should_match: 50%
,表示至少需要should
条件的一半匹配。- Combination values:可以结合固定数量值和百分比值,例如
minimum_should_match: "2<75%"
,表示至少需要两个should
条件匹配,或者匹配百分之75的should
条件。
# 我的filter有2个条件, should设置为0才能查询数据; filter和should的条件不冲突, filter只是影响should的默认值
# 如果有你filter则should的最小数量是0,如果没有should的最小数量就是1
GET test_goods/_search
{
"query": {
"bool": {
"filter": [
{
"range": {
"price": {
"gte": 10,
"lte": 99999
}
}
},
{
"term": {
"name.keyword": "apple phone"
}
}
],
"should": [
{
"match_phrase": {
"name": "huawei"
}
},
{
"match_phrase": {
"name": "phone"
}
}
,{
"bool": {
"must": [
{
"range": {
"price": {
"gte": 10,
"lte": 7000
}
}
}
]
}
}
],
"minimum_should_match": 2
}
}
}
must_not:必须不满足 不计算相关度分数 not子句(查询)不得出现在匹配的文档中。子句在过滤器上下文中执行,这意味着计分被忽略,并且子句被视为用于缓存。由于忽略计分,0因此将返回所有文档的分数。