elasticsearch version: 7.10.1
filter介绍
在Elasticsearch中,filter主要用于过滤文档,它与query的主要区别在于filter不计算相关性得分,而是返回简单的布尔匹配结果(匹配或不匹配),并且可以被缓存以提高性能。filter通常用于预筛选阶段,尤其是对于那些频繁使用的过滤条件。
filter语法
- Term Filter:
{
"query": {
"bool": {
"filter": {
"term": {
"field_name": "value"
}
}
}
}
}
- Range Filter
{
"query": {
"bool": {
"filter": {
"range": {
"age": {
"gte": 18,
"lte": 30
}
}
}
}
}
}
- Exists Filter
{
"query": {
"bool": {
"filter": {
"exists": {
"field": "category"
}
}
}
}
}
- List item
{
"query": {
"bool": {
"filter": {
"terms": {
"tags": ["tag1", "tag2"]
}
}
}
}
}
- And/Or Filters
{
"query": {
"bool": {
"filter": [
{ "term": { "color": "red" } },
{ "term": { "size": "large" } }
]
}
}
}
关键词 | 解释 |
---|---|
bool | |
term | term 查询适用于关键词类型的字段,用于匹配单个精确值 |
terms | terms 查询同样是针对关键词类型的字段,但它用于匹配多个精确值 |
查询流程
- 对每个filter条件进行布尔运算,决定哪些文档满足所有条件。由于filter不计算相关性得分,所以这一阶段非常快速,而且结果可以被缓存以优化后续的相同过滤查询
案例
场景
假设我们有一个电商产品索引,其中包含商品的详细信息,如product_id(产品ID)、name(产品名称)、category(产品类别)、price(价格)和brand(品牌)。现在我们需要创建一个索引,并插入大量文档,然后编写一个过滤查询,查找所有价格在一定范围内的电子产品(类别为electronics)。
索引创建
PUT /products
{
"mappings": {
"properties": {
"product_id": { "type": "keyword" },
"name": { "type": "text" },
"category": { "type": "keyword" },
"price": { "type": "double" },
"brand": { "type": "keyword" }
}
}
}
文档插入
POST /products/_bulk
{ "index": {} }
{ "product_id": "1", "name": "Apple iPhone X", "category": "electronics", "price": 999.99, "brand": "Apple" }
{ "index": {} }
{ "product_id": "2", "name": "Samsung Galaxy S20", "category": "electronics", "price": 799.99, "brand": "Samsung" }
{ "index": {} }
{ "product_id": "3", "name": "Bose QuietComfort Headphones", "category": "electronics", "price": 349.99, "brand": "Bose" }
POST /products/_bulk
{ "index": {} }
{ "product_id": "4", "name": "Dell XPS 13 Laptop", "category": "electronics", "price": 1299.99, "brand": "Dell" }
{ "index": {} }
{ "product_id": "5", "name": "Sony Alpha a7 III Camera", "category": "electronics", "price": 1999.99, "brand": "Sony" }
{ "index": {} }
{ "product_id": "6", "name": "Logitech MX Master 3 Mouse", "category": "electronics", "price": 99.99, "brand": "Logitech" }
{ "index": {} }
{ "product_id": "7", "name": "Microsoft Surface Pro 7", "category": "electronics", "price": 799.99, "brand": "Microsoft" }
{ "index": {} }
{ "product_id": "8", "name": "GoPro HERO9 Black Action Camera", "category": "electronics", "price": 399.99, "brand": "GoPro" }
查询语句
GET /products/_search
{
"query": {
"bool": {
"filter": [
{ "term": { "category": "electronics" } },
{ "range": {
"price": {
"gte": 500.00,
"lte": 1000.00
}
}
}
]
}
}
}