一.精確搜索,多個精確搜索
1.term
查詢
term
查詢可以用它處理數字(numbers)、布爾值(Booleans)、日期(dates)以及文本(text).
使用bulk創建文件文檔
POST /my_store/products/_bulk
{ "index": { "_id": 1 }}
{ "price" : 10, "productID" : "XHDK-A-1293-#fJ3" }
{ "index": { "_id": 2 }}
{ "price" : 20, "productID" : "KDKE-A-9947-#kL5" }
{ "index": { "_id": 3 }}
{ "price" : 30, "productID" : "JODL-X-1937-#pV7" }
{ "index": { "_id": 4 }}
{ "price" : 30, "productID" : "QQPX-R-3956-#aD8" }
{ "index": { "_id": 5 }}
{ "price" : 40, "productID" : "你好ds" }
term處理數字 :
在 Elasticsearch 的查詢表達式(query DSL)中,使用 term
查詢會查找我們指定的精確值。
constant_score
: 查詢以非評分模式
GET /my_store/products/_search
{
"query": {
"constant_score": {
"filter": {
"term": {
"price":40
}
}
}
}
}
term處理文本: 在處理文本的時候,ES的analyze
API會把文本才分成一個單詞,大寫的會變成小寫,特殊的字符會進行過濾
例如 :"XHDK-A-1293-#fJ3" 會才分成 "xhdk", "a","1293","fj3"
可以使用 GET /{索引}/_analyze 語法進行查詢才分的情況,如下
GET /my_store/_analyze { "field": "productID", "text": "XHDK-A-1293-#fJ3" }
term的文本查詢
GET /my_store/products/_search
{
"query" : {
"_score" : {
"filter" : {
"terms" : {
"productID": ["a","你"]
}
}
}
}
}
2.多個精確搜索
多個精確搜索,只要在 term
後面加個s
GET /my_store/products/_search { "query" : { "constant_score" : { "filter" : { "terms" : { "price" : [20, 30] } } } } }
二.組合過濾器
1.bool查詢
bool
(布爾)過濾器。 這是個 複合過濾器(compound filter) ,它可以接受多個其他過濾器作爲參數,並將這些過濾器結合成各式各樣的布爾(邏輯)組合。
bool
過濾器由三部分組成:
{ "bool" : { "must" : [], "should" : [], "must_not" : [], } }
must
: 所有的語句都 必須(must) 匹配,與 AND
等價。
must_not
: 所有的語句都 不能(must not) 匹配,與 NOT
等價。
should
: 至少有一個語句要匹配,與 OR
等價.
如此sql:
SELECT product FROM products
WHERE (price = 20 OR productID = "XHDK-A-1293-#fJ3")
AND (price != 30)
Elasticsearch中用bool表達此sql的語句 如下:
GET /my_store/products/_search { "query" : { "constant_score": { "filter" : { "bool" : { "should" : [//自少有一個條件符合 { "term" : {"price" : 20}}, { "term" : {"productID" : "fj3"}} ], "must_not" : {//排除條件 "term" : {"price" : 30} } } } } } }
三.範圍查詢
range
查詢
range
查詢可同時提供包含(inclusive)和不包含(exclusive)這兩種範圍表達式,可供組合的選項如下:
gt
:>
大於(greater than)lt
:<
小於(less than)gte
:>=
大於或等於(greater than or equal to)lte
:<=
小於或等於(less than or equal to)
如下事例:
GET /my_store/products/_search
{
"query" : {
"constant_score" : {
"filter" : {
"range" : {
"price" : {
"gte" : 20,
"lt" : 40
}
}
}
}
}
}
四.處理NULL值
1.exists
exists
:判斷不是NULL 與sql的 is not null 相同
使用ES的exists
表示 tags IS NOT NULL的判斷
SELECT tags FROM posts WHERE tags IS NOT NULL
如下
GET /my_index/posts/_search { "query" : { "constant_score" : { "filter" : { "exists" : { "field" : "tags" } } } } }
2.missing :
判斷是NULL 與sql的 is null 相同
使用ES的missing
表示 tags IS NULL的判斷
SELECT tags FROM posts WHERE tags IS NULL
如下:
GET /my_index/posts/_search { "query" : { "constant_score" : { "filter": { "missing" : { "field" : "tags" } } } } }