ES的过滤查询

ES的查询类型和特性

  • 查询(query):默认会计算每个返回文档的得分,然后根据得分排序
  • 过滤(filter):筛查出符合条件的文档,并且不计算得分,还可以缓存文档

image.png

注意:filter过滤查询必须要配合bool查询使用,执行时,先执行filter 过滤,然后在执行query,且ES会自动缓存经常使用的过滤器,以加快性能

filter过滤查询格式

GET /my_index/_search
{
	"query":{
  	"bool":{
    	"must":[
      	{"match_all":{}} // query 查询条件
      ],
    	"filter":[……]   // 过滤条件
    }
  }
}

term和terms查询

## term 单个关键词过滤查询
GET /my_index/_search
{
	"query":{
  	"bool":{
    	"must":[
      	{"match_all":{}} 
      ],
    	"filter":[
      	{
        	"term":{
          	"user":"LI LEI"
          }
        }
      ]
    }
  }
}

## terms 多个关键词过滤查询
GET /my_index/_search
{
	"query":{
  	"bool":{
    	"must":[
      	{"match_all":{}} 
      ],
    	"filter":[
      	{
        	"term":{
          	"user":["LI LEI","Tom"]
          }
        }
      ]
    }
  }
}

range 范围查询

GET /my_index/_search
{
	"query":{
  	"bool":{
    	"must":[
      	{"term":{
        		"user":{
          		"value":"zhangsan"
        		}
        	}
				} 
      ],
    	"filter":[
      	{
        	"range":{
          	"age":{
            	"gte":7,
            	"lte":20
						}
          }
        }
      ]
    }
  }
}

exists 过滤指定字段不为空的文档

GET /my_index/_search
{
	"query":{
  	"bool":{
    	"must":[
      	    {"term":{
            	"user":{
              	"value":"zhangsan"
            	}
            }
	  } 
      ],
    	"filter":[
      	{
        	"exists":{
          	"field":"telphoneNum"
          }
        }
      ]
    }
  }
}

ids 过滤查询

GET /my_index/_search
{
	"query":{
  	"bool":{
    	"must":[
      	{"term":{
          "user":{
        	"value":"zhangsan"
        	}
           }
	} 
      ],
    	"filter":[
      	{
        	"ids":{
          	"values":["1","2","3"]
          }
        }
      ]
    }
  }
}
posted @ 2022-10-16 11:41  Tenic  阅读(2014)  评论(0编辑  收藏  举报