[Elasticsearch]查詢語法速查

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爲準。

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中,使用matchterm效果是一樣的,表示包含此分詞。term性能稍勝10%。
相當於SQL:

SELECT COUNT(*) AS group_by_xxoo FROM index-1.type-x WHERE ftype=’file’ GROUP BY stype 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> mustmust_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

-_=! 太多關鍵字,都可以出本字典了。本人又編不下去了。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章