比较查询
与 must 类似,返回的文档必须满足 filter 子句的条件
与 must 不同的是:
- 不会计算分值,查询效率高
- 可以缓存结果,第二次查询效率高
应用场景不一样
如果结果需要算分就使用
must,否则可以考虑使用filter一般范围查询,用
filter,如:起止时间查询、年龄范围查询、地理位置范围查询
范围查询
must、filter都可以进行范围查询,需要 和 range 搭配使用,查询结果相同
大于、大于等于、小于、小于等于表示:
gt:大于gte:大于等于lt:小于lte:小于等于
filter
相当于 SQL:select * from toutiao_v1 where 200<like and like<=397
GET /toutiao_v1/_search
{
"query": {
"bool": {
"filter": {
"range": {
"like": {
"gt": 200,
"lte": 397
}
}
}
}
}
}
filter、must 和 should 同级时
- should 和 filter 同级,should 不生效
- should 和 must 同级,,should 不生效
should 不生效 案例
查询 like大于 200,并且 like 小于等于 397,并且 author 是 李雷 或者 lili 的记录,SQL语句如下:
select * from toutiao_v1 where 200< ilke and like <=397 and (author = '李雷' or author = 'lili' )
用DSL代码如下:
GET /toutiao_v1/_search
{
"query": {
"bool": {
"filter": {
"range": {
"like": {
"gt": 200,
"lte": 397
}
}
},
"should": [
{
"term": {
"author": "李雷"
}
},
{
"term": {
"author": "lili"
}
}
]
}
}
}
执行结果:
查询出 "author" : "李四",
原因: should 与 filter 同级时,should 不生效
解决方式一:minimum_should_match
加上 "minimum_should_match": 1 ,表示必须满足 must 和 filter 中的条件,并且必须满足 should 中的一个条件
GET /toutiao_v1/_search
{
"query": {
"bool": {
"minimum_should_match": 1, //其必须满足must和filter中的条件,并且必须满足should中的一个条件
"filter": {
"range": {
"like": {
"gt": 200,
"lte": 397
}
}
},
"should": [
{
"term": {
"author": "李雷"
}
},
{
"term": {
"author": "lili"
}
}
]
}
}
}
解决方式二:must
为了让 should 生效,需要在外面包一层 must
GET /toutiao_v1/_search
{
"query": {
"bool": {
"filter": [//filter
{
"range": {
"like": {
"gt": "200",//大于
"lte": "397"//小于等于
}
}
}
],
"must": { // should 外部又包了一层 must
"bool": {
"should": [//相当于sql中的 or
{
"term": {
"author": "李雷"
}
},
{
"term": {
"author": "lili"
}
}
]
}
}
}
}
}
解释:
