DSL 即领域特定语言(Domain Specific Language),是指为特定领域设定的专用语言。使用 Elasticsearch DSL 可以构建复杂的查询条件,在实际操作中最为轻量便捷。以下是主流 ES 版本常用的 DSL 分析。
ES 提供了基于 json 的完整 Query DSL 来定义查询。分为特定值查询和聚合查询,其中特定值查询主要有 match、term 和 range;聚合查询主要包含 bool 和 dis max。
ES 6.8及之前的版本支持的全文搜索类型为7种,分别是 Match Query、Match Phrase Query、Match Phrase Prefix Query、Multi Match Query、Common Terms Query、Query String Query 和 Simple Query String Query;7.0-7.1的版本新增了Intervals 类型;7.2及之后的版本新增了 Match boolean prefix 类型
match 查询是一种全文检索,包括模糊匹配选项。在查询时,首先分析查询字符串,然后根据分词构建查询对象,最后将结果返回。匹配查询在各版本之间的使用没有差别。
以下查询在默认分词器(standard)下,会分为“this”、“is”、“a”、“test”,根据此分词结果构造一个布尔值,当“query”字段中包含任一关键字时,都会返回此条 doc。
GET _search
{
"query": {
"match" : {
"message" : {
"query" : "this is tencent cloud"
}
}
}
}
此种查询方式基于以上的匹配查询方式,允许多字段 queries
GET _search
{
"query": {
"multi_match" : {
"query": "this is tencent cloud",
"fields": [ "subject", "message" ]
}
}
}
term 查询会返回字段中包含确切术语的 doc,是一种完全匹配。以下实例中,full_text 字段是 “text” 类型,默认分词器(standard)下,会分为“this”、“is”、“a”、“test”(均为小写),当直接搜索"This is A Test!"时,分词会去检索小写,所以返回无结果。
PUT my_index
{
"mappings" : {
"properties" : {
"full_text" : { "type" : "text" }
}
}
}
PUT my_index/_doc/1
{
"full_text": "This is Tencent Cloud!"
}
GET my_index/_search
{
"query": {
"term": {
"user": {
"full_text": "This is Tencent Cloud!"
}
}
}
}
以上两种查询方式的区别主要和字段的分词方式有关。match query 会先对查询值进行解析查询,而 term query 是将查询的 value 值直接返回。
主要涉及到 gt、gte、lt、lte 的使用
GET _search
{
"query": {
"range": {
"age": {
"lt": "100",
"gte": "18"
}
}
}
}
将多个查询条件组合在一起,是一种聚合查询,使用一个或多个布尔子句构建,每个子句都有特定类型,主要为这几种字句:“must”、“filter”、“must_not”和“should”。
POST _search
{
"query": {
"bool" : {
"must" : {
"term" : { "name" : "Tencent" }
},
"filter": {
"term" : { "product" : "elasticsearch service" }
},
"must_not" : {
"term" : { "region" : "nj" }
},
"should" : [
{ "match" : { "version" : "7.5.1" } },
{ "match" : { "CPU" : 8 } }
{ "match" : { "memory" : 16 } }
],
"boost" : 2.0
}
}
}
最佳匹配查询,将任何与任一查询匹配的文档作为结果返回,但只将最佳匹配的评分作为查询的评分结果返回。
GET _search
{
"query": {
"dis_max" : {
"queries" : [
{ "term" : { "title" : "Quick pets" }},
{ "term" : { "body" : "Quick pets" }}
],
"tie_breaker" : 0.7
}
}
}
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。