一、query DSL
叶子查询
于特定字段查询特定值。如 match
, term
或 range
查询
复合查询
包装其它叶子查询或复合查询。如使用 bool
or dis_max
混合多个查询
match_all
GET /_search { "query": { "match_all": {} } }
match
POST movies/_search { "query": { "match": { "title": "last christmas" } } } POST movies/_search { "query": { "match": { "title": { "query": "last christmas", "operator": "and" } } } }
match_phrase
POST movies/_search { "query": { "match_phrase": { "title":{ "query": "one love" } } } } POST movies/_search { "query": { "match_phrase": { "title":{ "query": "one love", "slop": 1 } } } }
布尔查询
POST _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" } } ], "minimum_should_match" : 1, "boost" : 1.0 } } }
常量查询,等价于只有一个 filter 子句的 bool 查询,所有匹配的得分都为 1.0
GET _search { "query": { "constant_score": { "filter": { "term": { "status": "active" } } } } }
命名子句,用于确定哪个子句命中匹配条件
GET /_search { "query": { "bool" : { "should" : [ {"match" : { "name.first" : {"query" : "shay", "_name" : "first"} }}, {"match" : { "name.last" : {"query" : "banon", "_name" : "last"} }} ], "filter" : { "terms" : { "name.last" : ["banon", "kimchy"], "_name" : "test" } } } } }
最佳字段查询
分离最大化查询(Disjunction Max Query)指的是: 将任何与任一查询匹配的文档作为结果返回,但只将最佳匹配的评分作为查询的评分结果返回,而不是将所有匹配结果的得分相加。
示例:
{ "query": { "dis_max": { "queries": [ { "match": { "title": "Brown fox" }}, { "match": { "body": "Brown fox" }} ] } } }
返回
{ "hits": [ { "_id": "2", "_score": 0.21509302, "_source": { "title": "Keeping pets healthy", "body": "My quick brown fox eats rabbits on a regular basis." } }, { "_id": "1", "_score": 0.12713557, "_source": { "title": "Quick brown rabbits", "body": "Brown rabbits are commonly seen." } } ] }
二、其它
分页、排序、source 过滤
#分页 POST /kibana_sample_data_ecommerce/_search { "from":10, "size":20, "query":{ "match_all": {} } } #对日期排序 POST kibana_sample_data_ecommerce/_search { "sort":[{"order_date":"desc"}], "query":{ "match_all": {} } } #source filtering POST kibana_sample_data_ecommerce/_search { "_source":["order_date"], "query":{ "match_all": {} } }
脚本
GET kibana_sample_data_ecommerce/_search { "script_fields": { "new_field": { "script": { "lang": "painless", "source": "doc['order_date'].value+'hello'" } } }, "query": { "match_all": {} } }
参考文档
https://www.elastic.co/guide/cn/elasticsearch/guide/current/_best_fields.html
https://www.elastic.co/guide/cn/elasticsearch/guide/current/_tuning_best_fields_queries.html
https://www.elastic.co/guide/en/elasticsearch/reference/7.6/query-dsl-bool-query.html
https://www.elastic.co/guide/en/elasticsearch/reference/7.6/query-dsl-match-query.html