0x00 SQL 轉 Query-DSL 插件,還用毛學DSL
法器在此: https://github.com/NLPchina/elasticsearch-sql/
0x01 基本語法
基本語法是 [GET|POST] http://domain.com/you_index_name/type1,type2/_search{?search_type=count|scan|…}
注意,隨着ES版本變化,搜索語法也有小調整。本文以1.7爲準。
- 全基於rest式http調用。 其中GET方法支持在body傳參數。
_search
是關鍵字,以此結束表示搜索行爲,可以同時搜索多個index與type。search_type
值爲count時,任何時候都不返回hits部分,減少返回內容;更多選項請參考:https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-search-type.html- body部分必需是
json
;同時支持 URL 中使用query_string
傳參; - 搜索請求會以
query_string
參數優先,且在 URL 中的參數有可能使用簡寫,如q==query。 - 可以同時索引多個index或type,逗號隔開,或直接使用
通配符
。 - 更豐富官方索引文檔在此 https://www.elastic.co/guide/en/elasticsearch/reference/current/search.html
0x02 例子:Group By
– 單條件
curl -XPOST 'http://localhost:9200/index-x/type-x/_search?search_type=count' -d'{
"aggs": {
"group_by_xxoo": {
"terms": {
"field": "stype"
}
}
},
"query": {
"term": { <1>
"ftype": "file"
}
},
"from": 0,
"size": 100
}'
<1>處的query中,使用match
或term
效果是一樣的,表示包含此分詞。term
性能稍勝10%。
相當於SQL:
SELECT COUNT(*) AS
group_by_xxoo
FROMindex-1
.type-x
WHEREftype
=’file’ GROUP BYstype
LIMIT 0, 100;
0x03 多條件查詢bool
:must、must_not、should
官方例子是:Query-DSL-bool-query(注:例子中少了query
這個key。)
{
"query": {
"bool": { <0>
"must": { <1>
"term": {
"user": "kimchy"
}
},
"must_not": {
"range": {
"age": {
"from": 10,
"to": 20
}
}
},
"should": [
{
"term": {
"tag": "wow"
}
},
{
"term": {
"tag": "elasticsearch"
}
}
],
"minimum_should_match": 1, <2>
"boost": 1 <3>
},
"from": 0,
"size": 100
}
}
<0> bool
稱爲query
的過慮器,還有很多過慮器,如:and
,or
,not
,limit
<1> must
、must_not
,should
爲過慮條件,如果多個子條件,使用[],如should
有兩個子條件。
<2> minimum_should_match
用於限制should
的子條件匹配個數。
<3> boost
表示此過慮器的權重,默認值1.0。
- 過慮器支持嵌套 – 呆 -_=!,可以寫一個很複雜的
Query-DSL
. - 由於
Query-DSL
查詢語言過於複雜無比,關鍵字非常多。本人編不下去了。用到再記下來。
0x04 Query-DSL
常用關鍵字:
query
,search_type
term
,terms
,match
,match_phrase
,multi_match
,fuzzy
bool
,and
,or
,not
,limit
,must
,must_not
,should
range
,size
,from
,to
,gt
,gte
,lt
,lte
field
,fields
aggs
,count
,sum
,min
,max
,avg
-_=! 太多關鍵字,都可以出本字典了。本人又編不下去了。