Query DSL 查询过滤 Filter 案例
filter 查询
- 来对搜索结果进行筛选和过滤,仅返回符合特定条件的文档,而不改变搜索评分
- Filter 查询对结果进行缓存,提高查询性能,用于数字范围、日期范围、布尔逻辑、存在性检查等各种过滤操作。
语法格式
filter 关键字用于指定一个过滤条件,可以是一个具体的过滤器,如 term、range 等,也可以是一个嵌套的 bool 过滤器
shell
{
"query": {
"bool": {
"filter": {
// 过滤条件
}
}
}
}查询案例数据环境准备
创建索引库
shell
PUT /product
{
"settings": {
"number_of_shards": 2,
"number_of_replicas": 0
},
"mappings": {
"properties": {
"product_id": {
"type": "integer"
},
"product_name": {
"type": "text"
},
"category": {
"type": "keyword"
},
"price": {
"type": "float"
},
"availability": {
"type": "boolean"
}
}
}
}导入数据
- 通过一次 POST 请求实现批量插入
- 每个文档都由两部分组成:index 指令用于指定文档的元数据,product_id 为文档的唯一标识符
- 插入后查询 GET /product/_search
shell
POST /product/_bulk
{ "index": { "_id": "1" } }
{ "product_id": 1, "product_name": "Product 1", "category": "books", "price": 19.99, "availability": true }
{ "index": { "_id": "2" } }
{ "product_id": 2, "product_name": "Product 2", "category": "electronics", "price": 29.99, "availability": true }
{ "index": { "_id": "3" } }
{ "product_id": 3, "product_name": "Product 3", "category": "books", "price": 9.99, "availability": false }
{ "index": { "_id": "4" } }
{ "product_id": 4, "product_name": "Product 4", "category": "electronics", "price": 49.99, "availability": true }
{ "index": { "_id": "5" } }
{ "product_id": 5, "product_name": "Product 5", "category": "fashion", "price": 39.99, "availability": true }案例一:使用 term 过滤器查询 category 为 books 的产品
shell
GET /product/_search
{
"query": {
"bool": {
"filter": {
"term": {
"category": "books"
}
}
}
}
}案例二:使用 range 过滤器查询价格 price 在 30 到 50 之间的产品
shell
GET /product/_search
{
"query": {
"bool": {
"filter": {
"range": {
"price": {
"gte": 30,
"lte": 50
}
}
}
}
}
}总结
- 过滤条件通常用于对结果进行筛选,并且比查询条件更高效
- 而 bool 查询可以根据具体需求组合多个条件、过滤器和查询子句
朔风