一、elasticsearch中的请求体查询详解
二、空查询
1、空查询会返回所有索引中所有文档
get /_search
2、只用一个查询字符串就可以在一个或者多个索引库中进行查询
get /test,drivers/_search
3、可以同时使用参数分页
get /_search { "from":1, "size":1 }
三、Query DSL查询语句
布尔查询参数:对应
must:文档必须匹配条件才能被包含进来,相当于and
must_not:文档必须不匹配条件才能被包含进来,相当于not and
should:文档只要匹配这些条件中任意一个,将被包含进来,相当于or
filter:必须匹配,不予以评分(对评分没有贡献),已过滤模式进行。
1、match_all 查询等价于空查询
{ "query":{ "match_all":{} } } match 查询包含关系
2、match查询 like
name字段包含zhang的文档
{ "query":{ "match":"zhang" } }
3、区间查询
data属于[2014-09-20,2014-09-24]
{ "query":{ "bool":{ "must":[ { "range":{ "data":{ "gt":"2014-09-20" } } }, { "range":{ "lt":"2014-09-24" } } ] } } } 一个bool语句,允许你在需要的时候组合其它语句无论是must匹配,mast_not匹配还是should匹配, 还有filter匹配
4、复杂区间查询
查询us索引库中date域大于2014-09-14
,tweet域包含elasticsearch
,date域不等于2014-09-16
,date域等于2014-09-22
{ "query": { "bool": { "must": [ { "range": { "date": { "gt": "2014-09-14" } } }, { "match": { "tweet": "elasticsearch" } } ], "must_not": { "term": { "date": "2014-09-16" } }, "filter": { "term": { "date": "2014-09-22" } } } } }
5、嵌套查询
- should可以进行or查询
查询tweet包含@mary,或者data大于2014-09-22
{ "query": { "bool": { "should": [ { "match": { "tweet": "@mary" } }, { "range": { "date": { "gt": "2014-09-22" } } } ] } } }
- should可以进行or查询,在加上must联合查询呢
查询(tweet域包含"@mary"或者date域大于"2014-09-22") 并且date域等于"2014-09-20"
{ "query": { "bool": { "should": [ { "match": { "tweet": "@mary" } }, { "range": { "date": { "gt": "2014-09-20" } } } ], "must": { "terms": { "date": ["2014-09-24", "2014-09-22"] } }, "minimum_should_match": 1 } } } 方法二 { "query": { "bool": { "must": [ { "terms": { "date": ["2014-09-22", "2014-09-24"] } }, { "bool": { "should": [ { "match": { "tweet": "@mary" } }, { "range": { "date": { "gt": "2014-09-22" } } } ] } } ] } } }
should在于must或者filter同级时,默认是不需要满足should中的任何条件的,此时我们可以加上minimum_should_match参数。也可以使用另外一种方式实现,即将should放到must中的一个bool条件中,即用分层的方式让should和must不同时出现;上述两种方法都可以解决should与must或者filter共存的问题。
6、查询与过滤
es查询时根据文档相关性(score)得分寻找最佳匹配,匹配度越高得分越高。
所有查询拥有变成不评分的能力,使用filter不得分,只过滤情况的查询,filter和should(或者must)联合使用,需要使用minimum_should_match:1
{ "query": { "bool": { "filter": [ { "match": {