es bool解释
概念Boolean query 可以基于多个条件的组合对文档进行查询。使用的是Lucene BooleanQuery的映射。它是基于一个或多个布尔子句构建的,每个子句对应一个类型。类型有以下几种:关键词描述must查询的结果必须匹配查询条件,并且计算score。filter查询的结果必须匹配查询条件,和must不太一样的是,不会计算scoreshould查询结果必须符合查询条件should中的一个
概念
Boolean query 可以基于多个条件的组合对文档进行查询。使用的是Lucene BooleanQuery的映射。它是基于一个或多个布尔子句构建的,每个子句对应一个类型。类型有以下几种:
关键词 | 描述 |
---|---|
must | 查询的结果必须匹配查询条件,并且计算score。 |
filter | 查询的结果必须匹配查询条件,和must不太一样的是,不会计算score |
should | 查询结果必须符合查询条件should中的一个或者多个,minimum_should_match参数定义了至少满足几个子句。会计算score。 |
must | 查询的结果必须不符合查询条件。 |
注意
bool查询采用的策略是“越多的匹配越好”,所以每个命中的must和should语句都会计算score,最终会为每个文档计算一个总分。
如下官方文档示意:
需要数据的user.id为kimchy
tags包含production
并且age要小于10且大于20
tags至少要包含env1或者deployed
curl -X POST "localhost:9200/_search?pretty" -H 'Content-Type: application/json' -d'
{
"query": {
"bool" : {
"must" : {
"term" : { "user.id" : "kimchy" }
},
"filter": {
"term" : { "tags" : "production" }
},
"must_not" : {
"range" : {
"age" : { "gte" : 10, "lte" : 20 }
}
},
"should" : [
{ "term" : { "tags" : "env1" } },
{ "term" : { "tags" : "deployed" } }
],
"minimum_should_match" : 1,
"boost" : 1.0
}
}
}
'
使用minimum_should_match
如上文所提,可以使用minimum_should_match去设置文档中必须匹配的should子句数量或者百分比。
如果bool查询中,使用了至少一个1个should语句,并且没有用过must和filter语句,默认的值是1,否则默认值是0。
bool.filter的得分
在filter中的命中的元素对score没有影响-score会return 0.分数仅受特别指定的查询的影响。举例,下面三个会返回所有status包含分词active的文档。
GET _search
{
"query": {
"bool": {
"filter": {
"term": {
"status": "active"
}
}
}
}
}
虽然有match_all,但是为每个文档都分配了1.0的score。
curl -X GET "localhost:9200/_search?pretty" -H 'Content-Type: application/json' -d'
{
"query": {
"bool": {
"must": {
"match_all": {}
},
"filter": {
"term": {
"status": "active"
}
}
}
}
}
'
constant_score和上面的那个例子一样,constant_score为命中filter的每个文档都分配了1.0的score。
curl -X GET "localhost:9200/_search?pretty" -H 'Content-Type: application/json' -d'
{
"query": {
"constant_score": {
"filter": {
"term": {
"status": "active"
}
}
}
}
}
'
name声明
每个查询支持一个_name在最顶层的定义。可以使用命名查询来跟踪哪些查询与返回的文档匹配。如果使用命名查询,则响应会为每个命中的文档包含一个matched_queries 属性。
curl -X GET "localhost:9200/_search?pretty" -H 'Content-Type: application/json' -d'
{
"query": {
"bool": {
"should": [
{ "match": { "name.first": { "query": "shay", "_name": "first" } } },
{ "match": { "name.last": { "query": "banon", "_name": "last" } } }
],
"filter": {
"terms": {
"name.last": [ "banon", "kimchy" ],
"_name": "test"
}
}
}
}
}
'
更多推荐
所有评论(0)