简介
es所有查询会触发相关度计算, 对于那些不需要相关度得分的场景下. es以过滤器的形式提供另一种查询.
过滤器类似查询, 但是他们更快, 主要有以下原因
- 过滤器不会计算相关度的得分,所以它们在计算上更快一些。
- 过滤器可以被缓存到内存中,这使得在重复的搜索查询上,其要比相应的查询快出许多。
可以将一个查询(像是match_all,match,bool等)和一个过滤器结合起来。我们 以范围过滤器为例,它允许我们通过一个区间的值来过滤文档。这通常被用在数字和日期的过滤上。 下面这个例子使用一个被过滤的查询,其返回price值是在200到1000之间(闭区间)的书。
POST /book/_search
{
"query": {
"bool": {
"must": {
"match_all": {}
},
"filter": {
"range": {
"price": {
"gte": 200,
"lte": 1000
}
}
}
}
}
}
POST /book/_search
{
"query": {
"bool": {
"must": {
"match_all": {}
},
"filter": {
"term": {
"price": "320.45"
}
}
}
}
}
上面的例子,被过滤的查询包含一个match_all查询(查询部分)和一个过滤器(filter部分)。
我们可以在查询部分中放入其他查询,在filter部分放入其它过滤器
filter和bool过滤查询
POST /products/_bulk
{"index":{"_id":1}}
{"price":10,"productID":"SD1002136"}
{"index":{"_id":2}}
{"price":20,"productID":"SD2678421"}
{"index":{"_id":3}}
{"price":30,"productID":"SD8897573"}
{"index":{"_id":4}}
{"price":30,"productID":"SD4535233"}
select product from products where (price = 20 or productID= "SD1002136") and (price != 30);
# 查询价格等于20的或者productID为SD1002136的商品,排除价格30元的
类似的,elasticsearch也有and,or,not这样的组合条件的查询方式
格式如下
{
"bool": {
"must":[],
"should":[],
"must_not":[],
}
}
must条件必须满足,相当于and
should:条件可以满足也可以不满足,相当于or
must_not:条件不需要,相当于not
GET /products/_search
{
"query": {
"bool": {
"filter": {
"bool": {
"should": [
{"term": {"price": 20}},
{"term": {"productID": "SD1002136"}}
],
"must_not": {
"term": {"price": 30}
}
}
}
}
}
}
范围查询
gt > 大于
lt < 小于
gte >= 大于等于
lte <= 小于等于
# form和to也行
POST /book/_search
{
"query": {
"bool": {
"must": {
"match_all": {}
},
"filter": {
"range": {
"price": {
"from": 200,
"to": 1000
}
}
}
}
}
}
嵌套查询
GET /book/_search
{
"query": {
"bool": {
"filter": {
"bool": {
"should": [
{"term": {"price": 320.45}},
{ "bool": {
"must": [
{"term": {"name": "solr"}}
]
}}
]
}
}
}
}
}