一、元數據
1、從索引中查詢出的結果可以稱之為元數據,如下圖
2、可以禁止元數據的展示(一般不使用)
使用如下代碼查詢后,元數據將不再展示
1 GET product/_search 2 { 3 "_source": false, 4 "query": { 5 "match_all": {} 6 } 7 }
好處:節省存儲開銷
壞處:不支持update、update_by_query、reindex API
3、數據源過濾器
第一種:使用下圖這種形式設置索引mapping,查詢結果中只會包含name和price,不會包含desc和tags
1 PUT product1 2 { 3 "mappings": { 4 "_source": { 5 "includes": [ 6 "name", 7 "price" 8 ], 9 "excludes": [ 10 "desc", 11 "tags" 12 ] 13 } 14 } 15 }
第二種:在查詢時指定include和exclude字段
1 GET product/_search 2 { 3 "_source": { 4 "includes": [ 5 "name" 6 ], 7 "excludes": [ 8 "age" 9 ] 10 }, 11 "query": { 12 "match_all": {} 13 } 14 }
二、全文檢索
1、match:根據字段進行匹配。select * from table where name = '';
2、match_all:無條件匹配。select * from table;
3、multi_match:從指定“字段中匹配。select * from table where name=shouji and age=shouji;
1 GET product/_search 2 { 3 "query": { 4 "multi_match": { 5 "query": "shouji", 6 "fields": ["name","age"] 7 } 8 } 9 }
4、match_phrase:會被分詞
被檢索字段必須包含match_phrase中的所有詞項並且順序必須相同
被檢索字段包含的match_phrase中的詞項之間不能有其他問題
1 GET product/_search 2 { 3 "query": { 4 "match_phrase": { 5 "name": "my name" 6 } 7 } 8 }
如上代碼:查詢的name字段必須為my name,不能為my xx name、name my
三、精准查詢
term:搜索詞不會被分詞
1、如下圖查詢沒有結果是因為:搜索詞沒有被分詞,所以my name lyc被當成一個整體。但是索引中my name lyc被分成了my、name、lyc。所有沒有匹配記錄
2、如下圖就有結果,因為搜索詞沒有被分詞,而索引中name字段取了keyword,也不會被分詞。所以有匹配結果
3、terms
1 GET product/_search 2 { 3 "query": { 4 "terms": { 5 "tags": [ 6 "lowbee", 7 "gongjiaoka" 8 ] 9 } 10 } 11 }
4、range:范圍查詢
1 GET product/_search 2 { 3 "query": { 4 "range": { 5 "price": { 6 "gte": 10, 7 "lte": 20 8 } 9 } 10 } 11 }
四、過濾器
作用:篩選數據,不會計算相關度評分,提高效率
而query則是會計算相關度評分的
若數據量非常大的時候使用filter會降低性能開銷
五、組合查詢(bool query)
1、must:所有條件都必須符合相當於sql中的and
使用下面代碼查詢出的結果有相關度評分
1 GET product/_search 2 { 3 "query": { 4 "bool": { 5 "must": [ 6 { 7 "match": { 8 "name": "lyc" 9 } 10 } 11 ] 12 } 13 } 14 }
2、filter:將上圖中must替換為filter。替換后查出的結果相關度評分為0。
3、must_not:所有條件都不符合的結果
4、should:或者,相當於sql中的or
5、must與filter組合使用
下面代碼為must與filter組合使用,若樣本很多時,可以先使用filter進行過濾(filter不計算相關度分數,節省了性能消耗),之后再使用match計算相關度評分。
1 GET product/_search 2 { 3 "query": { 4 "bool": { 5 "must": [ 6 { 7 "match": { 8 "name": "lyc" 9 } 10 } 11 ], 12 "filter": [ 13 { 14 "range": { 15 "age": { 16 "gte": 10 17 } 18 } 19 } 20 ] 21 } 22 } 23 }
6、should與filter或must組合使用時
minimum_should_match:若沒有這個參數,should條件可以被忽略(不匹配)。后面的數字表示需要有幾個should滿足條件(若組合查詢有must或者filter時該參數默認為0;若只有should,該參數默認為1;若需要滿足其他場景,該參數需要手動設置)
1 GET product/_search 2 { 3 "query": { 4 "bool": { 5 "filter": [ 6 { 7 "range": { 8 "age": { 9 "gte": 10 10 } 11 } 12 } 13 ], 14 "should": [ 15 { 16 "match_phrase": { 17 "name": "my name" 18 } 19 } 20 ], 21 "minimum_should_match": 1 22 } 23 } 24 }