Elasticsearch——filter过滤查询

1. filter

filter,就是按照搜索条件过滤出须要的数据,不计算任何相关度分数,对相关度没有影响json

2. filter 与 query 对比

  1. filter,按照搜索条件过滤出须要的数据,不计算任何相关度分数,对相关度没有影响
  2. query,会去计算每一个document相对于搜索条件的相关度,并按照相关度进行排序

在实际开发中,若是须要把最匹配搜索条件的数据先返回,那么用query,果只是要根据一些条件筛选出一部分数据,不关注其排序,那么用filter。app

3. filter 与 query 性能

  • filter,不须要计算相关度分数,不须要按照相关度分数进行排序,同时还有内置的自动cache最常使用filter的数据, 性能好
  • query,要计算相关度分数,按照分数进行排序,并且没法cache结果.

4. 查询示例

 1GET /ecommerce/product/_search
2{
3  "query": {
4    "bool": {
5      "must": [
6        {
7          "match": {
8            "name""yagao"
9          }
10        }
11      ],
12      "should": [
13        {
14          "match": {
15            "producer""yagao"
16          }
17
18        }
19      ],
20      "filter": {
21        "range": {
22          "price": {
23            "gte"25,
24            "lt"50
25          }
26        }
27      }
28    }
29  },
30  "sort": [
31    {
32      "price": {
33        "order""desc"
34      }
35    }
36  ]
37}
复制代码

返回结果:性能

 1{
2  "took"0,
3  "timed_out"false,
4  "_shards": {
5    "total"5,
6    "successful"5,
7    "skipped"0,
8    "failed"0
9  },
10  "hits": {
11    "total"3,
12    "max_score"null,
13    "hits": [
14      {
15        "_index""ecommerce",
16        "_type""product",
17        "_id""3",
18        "_score"null,
19        "_source": {
20          "name""zhonghua yagao",
21          "desc""caoben zhiwu",
22          "price"40,
23          "producer""zhonghua producer",
24          "tags": [
25            "qingxin"
26          ]
27        },
28        "sort": [
29          40
30        ]
31      },
32      {
33        "_index""ecommerce",
34        "_type""product",
35        "_id""1",
36        "_score"null,
37        "_source": {
38          "name""gaolujie yagao",
39          "desc""gaoxiao meibai",
40          "price"30,
41          "producer""gaolujie producer",
42          "tags": [
43            "meibai",
44            "fangzhu"
45          ]
46        },
47        "sort": [
48          30
49        ]
50      },
51      {
52        "_index""ecommerce",
53        "_type""product",
54        "_id""2",
55        "_score"null,
56        "_source": {
57          "name""jiajieshi yagao",
58          "desc""youxiao fangzhu",
59          "price"25,
60          "producer""jiajieshi producer",
61          "tags": [
62            "fangzhu"
63          ]
64        },
65        "sort": [
66          25
67        ]
68      }
69    ]
70  }
71}
复制代码

因为咱们按照价格降序排列,因此没有计算相关度,_score都等于nullspa

注意code

对于range查询,单独使用语法为:orm

 1GET /ecommerce/product/_search
2{
3  "query": {
4    "range": {
5      "price": {
6        "gte"20,
7        "lte"50
8      }
9    }
10  }
11}
复制代码

这样能返回结果,可是若是多条件查询和range查询一块儿使用的话,须要将range放在bool查询的filter中,好比第一个例子。排序

相关文章
相关标签/搜索