1. filter
filter,就是按照搜尋條件過濾出需要的資料,不計算任何相關度分數,對相關度沒有影響
2. filter 與 query 對比
- filter,按照搜尋條件過濾出需要的資料,不計算任何相關度分數,對相關度沒有影響
- query,會去計算每個document相對於搜尋條件的相關度,並按照相關度進行排序
在實際開發中,如果需要把最匹配搜尋條件的資料先返回,那麼用query,果只是要根據一些條件篩選出一部分資料,不關注其排序,那麼用filter。
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都等於null
注意:
對於range查詢,單獨使用語法為:
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中,比如第一個例子。