Elasticsearch 提供了豐富的查詢過濾語句,本文整理了一些常用的查詢方法。
ES 有兩種查詢方式。本文主要介紹基於DSL語法的查詢
- 使用 Search Lite API,它從url中獲取參數
- 使用 Json 作爲請求體,使用 ES的DSL語法來進行查詢
1. 全文級別查詢
match 是一個標準查詢,可以查詢文本、數字、日期格式的數據。match 查詢的一個主要用途是全文檢索。ES 5.X 以上的版本默認使用BM25算法進行相似度的計算
GET /_search
{
"query": {
"match" : {
"message" : "hello world"
}
}
}
match_phrase 與match查詢不同,它是精確匹配
GET /_search
{
"query": {
"match_phrase" : {
"message" : "this is a test"
}
}
}
multi_match 允許在做match 查詢的基礎上查詢多個字段
GET /_search
{
"query":{
"multi_match": {
"query": "full text search",
"fields": [ "title", "body" ]
}
}
}
2. 詞條級別查詢
term 用於精確值的查詢。使用boost參數可以提高指定字段的分數。boost的默認值爲1。
string類型的數據在ES中可以使用text或者keyword的類型來存儲。ES存儲text類型的數據時會自動分詞,然後建立索引。keyword存儲數據時,不會分詞,直接建立索引。如果需要對string數據進行精確查詢,應該使用keyword的類型來存儲數據。
GET /_search
{
"query":{
"bool":{
"should":[
{
"term":{
"status":{
"value":"urgent",
"boost":2
}
}
},
{
"term":{
"status":"normal"
}
}
]
}
}
}
terms 可以指定一個字段的多個精確值。
GET /_search
{
"query": {
"constant_score" : {
"filter" : {
"terms" : { "user" : ["kimchy", "elasticsearch"]}
}
}
}
}
range 用於需要查詢指定範圍的內容。range 的常用參數有gte (greater-than or equal to), gt (greater-than) ,lte (less-than or equal to) 和 lt (less-than)。ES 的date類型的數值也可以使用range查詢。
GET /_search
{
"query": {
"range" : {
"age" : {
"gte" : 10,
"lte" : 20,
"boost" : 2.0
}
}
}
}
exists 返回在原始字段匯中至少有一個非空值的文檔
GET /_search
{
"query": {
"exists" : { "field" : "user" }
}
}
prefix 前綴查詢
GET /_search
{
"query": {
"prefix": {
"postcode": "W1"
}
}
}
3. 複合查詢
bool 查詢可以合併多個過濾條件查詢的結果。bool 查詢可由 must, should, must not, filter 組合完成
- must 查詢的內容必須出現在檢索到的文檔中,並且會計算文檔匹配的相關度
- filter 查詢的內容必須出現在檢索到的文檔中。與must不同,filter中的查詢條件不會參與評分。filter對查詢的數據有緩存功能。filter效率會比must高一些,一般,除了需要計算相關度的查詢,一般使用filter
- should 至少有一個查詢條件匹配,相當於 or
- must_mot 多個查詢條件的相反匹配,相當於 not
GET /_search
{
"query":{
"bool":{
"must":{
"term":{
"user":"kimchy"
}
},
"filter":{
"term":{
"tag":"tech"
}
},
"must_not":{
"range":{
"age":{
"gte":10,
"lte":20
}
}
},
"should":[
{
"term":{
"tag":"wow"
}
},
{
"term":{
"tag":"elasticsearch"
}
}
]
}
}
}