filter是不計算相關性的,同時可以cache,因此,filter速度要快於query
1、准備數據
POST /lib/items/_bulk {"index":{"_id":1}} {"price":40,"itemID":"ID100123"} {"index":{"_id":2}} {"price":50,"itemID":"ID100124"} {"index":{"_id":3}} {"price":25,"itemID":"ID100125"} {"index":{"_id":4}} {"price":30,"itemID":"ID100126"} {"index":{"_id":5}} {"price":null,"itemID":"ID100127"}
2、操作演示
1)查詢price是40的;查詢price是25或者40的
GET /lib/items/_search { "query":{ "bool":{ "filter":[ {"term":{"price":40}} ] } } } GET /lib/items/_search { "query":{ "bool":{ "filter":[ {"terms":{"price":[25,40]}} ] } } }
2)查詢itemID是ID100123的,用第一種方式查詢不出來,因為創建時itemID的mapping類型默認是text,存儲時分詞,存儲的是id100123。默認小寫。
#查詢不出 GET /lib/items/_search { "query":{ "bool":{ "filter":[ {"term":{"itemID":"ID100123"}} ] } } } #能查詢出 GET /lib/items/_search { "query":{ "bool":{ "filter":[ {"term":{"itemID":"id100123"}} ] } } }
或者自定義mapping,改為不分詞的:
#查看mapping GET /lib7/_mapping #刪除mapping DELETE lib7 #重新創建mapping PUT /lib7 { "mappings":{ "items":{ "properties":{ "itemID":{ "type":"text", "index":false } } } } }
3)bool過濾查詢。可以實現組合過濾查詢,格式如下 :
{"bool":{"must":[],"should":[],"must_not":[]}}
must:必須滿足的條件---and
should:可以滿足也可以不滿足的條件---or
must_not:不需要滿足的條件-----not
3.1)查詢price是25或者itemID是id100123的 並且 price不能是30
GET /lib/items/_search { "post_filter":{ "bool":{ "should":[ {"term":{"price":25}}, {"term":{"itemID":"id100123"}} ], "must_not":{ "term":{"price":30} } } } } #或者 GET /lib/items/_search { "query":{ "bool":{ "should":[ {"term":{"price":25}}, {"term":{"itemID":"id100123"}} ], "must_not":{ "term":{"price":30} } } } }
3.2)嵌套使用bool:要么id100123,要么(id是100124價格是40)並且價格 不能是30
GET /lib/items/_search { "post_filter":{ "bool":{ "should":[ {"term":{"itemID":"id100123"}}, {"bool":{"must":[ {"term":{"itemID":"id100124"}}, {"term":{"price":40}} ]}} ], "must_not":{ "term":{"price":30} } } } }
4)范圍過濾。gt:>;lt:<;gte:>=;lte:<=
4.1)price價格大於25且小於50的
GET /lib/items/_search { "post_filter":{ "range":{ "price":{ "gt":25,"lt":50 } } } }
4.2)查詢價格不是null的
GET /lib/items/_search { "query":{ "bool":{ "filter":{ "exists":{ "field":"price" } } } } }
