[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

-_=! 太多关键字,都可以出本字典了。本人又编不下去了。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值