Query DSL
Domain Specific Language领域专用语言Elasticsearch provides a full Query DSL based on JSON to define queries
Elasticsearch 提供了基于 JSON 的 DSL 来定义查询。
DSL 由叶子查询子句和复合查询子句两种子句组成。
本文适配 Elasticsearch 7.x 版本
推荐学习阮一鸣《Elasticsearch 核心技术与实战》
Elasticsearch 查询层级图
在 query 上下文和 filter 上下文中,查询子句的行为会有所不同。(Query and filter context)
filter context 有缓存、不算分,查询速度更快
Leaf query clauses,叶子查询子句
Full text queries,全文查询
intervalsmatchmatch_bool_prefixmatch_phrasematch_phrase_prefixmulti_matchquery_stringsimple_query_string
示例
GET /_search{ "query": { "match": { "message": { "query": "this is a test" } } }}
Term-level queries
existsfuzzyidsprefixrangeregexptermtermsterms_settypewildcard
示例
GET my_index/_search?pretty{ "query": { "term": { "full_text": "Quick Brown Foxes!" } }}
示例
GET _search{ "query": { "range": { "age": { "gte": 10, "lte": 20, "boost": 2 } } }}
Compound query clauses,复合查询子句
布尔查询的子句类型有四种: must、filter、should、must_not
must算分返回的文档必须满足 must 子句的条件多个查询条件的完全匹配,相当于 AND
filter不算分的 must
should算分在一个 bool 查询中,如果没有 must 或者 filter,有一个或者多个should子句,那么只要满足一个就可以返回。minimum_should_match 参数定义了至少满足几个子句至少有一个查询条件匹配,相当于 OR
must_not不算分返回的文档必须不满足 must_not 定义的条件多个查询条件的相反匹配,相当于 NOT
示例
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 } }}
示例
GET /_search{ "query": { "boosting": { "positive": { "term": { "text": "apple" } }, "negative": { "term": { "text": "pie tart fruit crumble tree" } }, "negative_boost": 0.5 } }}
示例
GET /_search{ "query": { "constant_score": { "filter": { "term": { "user": "kimchy" } }, "boost": 1.2 } }}
示例
GET /_search{ "query": { "dis_max": { "queries": [ { "term": { "title": "Quick pets" } }, { "term": { "body": "Quick pets" } } ], "tie_breaker": 0.7 } }}
示例
GET /_search{ "query": { "function_score": { "query": { "match_all": {} }, "boost": "5", "random_score": {}, "boost_mode": "multiply" } }}
本文出自 walker snapshot
联系客服