Query DSL
Elasticsearch 查询语句采用基于 RESTful 风格的接口封装成 JSON 格式的对象,称之为 Query DSL。
Elasticsearch 查询分类大致分为全文查询、词项查询、复合查询、嵌套查询、地理位置查询、特殊查询
。
查询机制
关键字查询
- 一种是根据用户输入的查询词,通过排序模型计算文档与查询词之间的相关度,并根据评分从高到低排序返回;
过滤查询 - 过滤机制,只根据过滤条件对文档进行过滤,不计算评分,**
速度相对较快
**
全文查询
match query
match query 用于搜索单个字段,首先会针对查询语句进行解析(经过 analyzer),
analyzer:主要是对查询语句进行分词,分词后查询语句的任何一个词项被匹配,文档就会被搜到,默认情况下相当于对分词后词项进行 or 匹配操作。
// GET article/_search
{
"query": {
"match": {
"title": {
"query": "Elasticsearch 查询优化"
}
}
}
}
// 等同于 or 匹配操作
// GET article/_search
{
"query": {
"match": {
"title": {
"query": "Elasticsearch 查询优化",
"operator": "or"
}
}
}
}
// 查询匹配所有关键词的文档,可以用 and 操作符连接
// GET article/_search
{
"query": {
"match": {
"title": {
"query": "Elasticsearch 查询优化",
"operator": "and"
}
}
}
}
match_phrase query
match_phrase query 首先会把 query 内容分词,分词器可以自定义,同时文档还要满足以下两个条件才会被搜索到:
分词后所有词项都要出现在该字段中(相当于 and 操作)。
字段中的词项顺序要一致。
例如,有以下 3 个文档,使用 match_phrase 查询“what a wonderful life”,只有前两个文档会被匹配:
// PUT test_idx/test_tp/1
{ "desc": "what a wonderful life" }
// PUT test_idx/test_tp/2
{ "desc": "what a life"}
// PUT test_idx/test_tp/3
{ "desc": "life is what"}
// GET test_idx/test_tp/_search
{
"query": {
"match_phrase": {
"desc": "what life"
}
}
}
match_phrase_prefix query
match_phrase_prefix query
match_phrase_prefix 和 match_phrase 类似,只不过 match_phrase_prefix 支持最后一个 term 的前缀匹配。
// GET test_idx/test_tp/_search
{
"query": {
"match_phrase_prefix": {
"desc": "what li"
}
}
}
multi_match query
multi_match 是 match 的升级,用于搜索多个字段。查询语句为“java 编程”,查询域为 title 和 description,查询语句如下:
// GET books/_search
{
"query": {
"multi_match": {
"query": "java 编程",
"fields": ["title", "description"]
}
}
}
// multi_match 支持对要搜索的字段的名称使用通配符,示例如下:
// GET books/_search
{
"query": {
"multi_match": {
"query": "java 编程",
"fields": ["title", "*_name"]
}
}
}
// 用指数符号指定搜索字段的权重。指定关键词出现在 title 中的权重是出现在 description 字段中的 3 倍,命令如下:
// GET books/_search
{
"query": {
"multi_match": {
"query": "java 编程",
"fields": ["title^3", "description"]
}
}
}
common_terms query
common_terms query 是一种在不牺牲性能的情况下替代停用词提高搜索准确率和召回率的方案。
该查询在 elasticsearch 7.3.0 版本及之后废弃。
词项查询
term query
term 查询不被解析,精确匹配才会被搜索到,应用场景为查询人名、地名等需要精准匹配的需求
注意:
禁止 term 查询对 text 字段使用查询。
要搜索 text 字段值,需改用 match 查询。
terms query
terms 查询是 term 查询的升级,可以用来查询文档中包含多个词的文档。比如,想查询 title 字段中包含关键词 “java” 或 “python” 的文档,构造查询语句如下:
{
"query": {
"terms": {
"title": ["java", "python"]
}
}
}
range query
范围查询,用于匹配在某一范围内的数值型、日期类型或者字符串型字段的文档
使用 range 查询只能查询一个字段,不能作用在多个字段上
range 查询支持的参数有以下几种:
- gt 大于,查询范围的最小值,也就是下界,但是不包含临界值。
- gte 大于等于,和 gt 的区别在于包含临界值。
- lt 小于,查询范围的最大值,也就是上界,但是不包含临界值。
- lte 小于等于,和 lt 的区别在于包含临界值。
// GET bookes/_search
{
"query": {
"range": {
"price": {
"gt": 50,
"lte": 70
}
}
}
}
exists query
非空查询,exists 查询会返回字段中至少有一个非空值的文档
匹配项:
- { “user” : “jane” } 有 user 字段,且不为空。
- { “user” : “” } 有 user 字段,值为空字符串。
- { “user” : “-“ } 有 user 字段,值不为空。
- { “user” : [ “jane” ] } 有 user 字段,值不为空。
- { “user” : [ “jane”, null ] } 有 user 字段,至少一个值不为空即可。
非匹配项
- { “user” : null } 虽然有 user 字段,但是值为空。
- { “user” : [] } 虽然有 user 字段,但是值为空。
- { “user” : [null] } 虽然有 user 字段,但是值为空。
- { “foo” : “bar” } 没有 user 字段
prefix query
前缀查询
prefix 查询用于查询某个字段中以给定前缀开始的文档,比如查询 title 中含有以 java 为前缀的关键词的文档,那么含有 java、javascript、javaee 等所有以 java 开头关键词的文档都会被匹配。查询 description 字段中包含有以 win 为前缀的关键词的文档,查询语句如下
// GET books/_search
{
"query": {
"prefix": {
"description": "win"
}
}
}
wildcard query通配符查询
支持单字符通配符和多字符通配符,**? 用来匹配一个任意字符,* 用来匹配零个或者多个字符**
和 prefix 查询一样,wildcard 查询的查询性能也不是很高,需要消耗较多的 CPU 资源
下面举一个 wildcard 查询的例子,假设需要找某一作者写的书,但是忘记了作者名字的全称,只记住了前两个字,那么就可以使用通配符查询,查询语句如下:
GET books/_search
{
"query": {
"wildcard": {
"author": "李永*"
}
}
}
regexp query
正则表达式查询
Elasticsearch 也支持正则表达式查询,通过 regexp query 可以查询指定字段包含与指定正则表达式匹配的文档。可以代表任意字符, “a.c.e” 和 “ab…” 都可以匹配 “abcde”,a{3}b{3}、a{2,3}b{2,4}、a{2,}{2,} 都可以匹配字符串 “aaabbb”。
例如需要匹配以 W 开头紧跟着数字的邮政编码,使用正则表达式查询构造查询语句如下:
// GET books/_search
{
"query": {
"regexp": {
"postcode": "W[0-9].+"
}
}
}
type query
type query 用于查询具有指定类型的文档。例如查询 Elasticsearch 中 type 为 computer 的文档,查询语句如下:
// GET books/_search
{
"query": {
"type": {
"value": "computer"
}
}
}
ids query
ids query 用于查询具有指定 id 的文档。类型是可选的,也可以省略,也可以接受一个数组。如果未指定任何类型,则会查询索引中的所有类型。例如,查询类型为 computer,id 为 1、3、5 的文档,本质上是对文档 _id 的查询,所以对应的 value 是字符串类型,查询语句如下:
// GET books/_search
{
"query": {
"ids": {
"type": "computer",
"values": ["1", "3", "5"]
}
}
}
复合查询
复合查询就是把一些简单查询组合在一起实现更复杂的查询需求,除此之外,复合查询还可以控制另外一个查询的行为。
bool query
bool 查询可以把任意多个简单查询组合在一起,使用 must、should、must_not、filter 选项来表示简单查询之间的逻辑,每个选项都可以出现 0 次到多次,它们的含义如下:
must 文档必须匹配 must 选项下的查询条件,相当于逻辑运算的 AND,且参与文档相关度的评分。
should 文档可以匹配 should 选项下的查询条件也可以不匹配,相当于逻辑运算的 OR,且参与文档相关度的评分。
must_not 与 must 相反,匹配该选项下的查询条件的文档不会被返回;需要注意的是,must_not 语句不会影响评分,它的作用只是将不相关的文档排除。
filter 和 must 一样,匹配 filter 选项下的查询条件的文档才会被返回,但是 filter 不评分,只起到过滤功能,与 must_not 相反。
假设要查询 title 中包含关键词 java,并且 price 不能高于 70,description 可以包含也可以不包含虚拟机的书籍,构造 bool 查询语句如下:
GET books/_search
{
“query”: {
“bool”: {
“filter”: {
“term”: {
“status”: 1
}
},
“must_not”: {
“range”: {
“price”: {
“gte”: 70
}
}
},
“must”: {
“match”: {
“title”: “java”
}
},
“should”: [
{
“match”: {
“description”: “虚拟机”
}
}
],
“minimum_should_match”: 1
}
}
}
有关布尔查询更详细的信息参考 bool query(组合查询)详解。
boosting query
boosting 查询用于需要对两个查询的评分进行调整的场景,boosting 查询会把两个查询封装在一起并降低其中一个查询的评分。
boosting 查询包括 positive、negative 和 negative_boost 三个部分,positive 中的查询评分保持不变,negative 中的查询会降低文档评分,negative_boost 指明 negative 中降低的权值。如果我们想对 2015 年之前出版的书降低评分,可以构造一个 boosting 查询,查询语句如下:
GET books/_search
{
“query”: {
“boosting”: {
“positive”: {
“match”: {
“title”: “python”
}
},
“negative”: {
“range”: {
“publish_time”: {
“lte”: “2015-01-01”
}
}
},
“negative_boost”: 0.2
}
}
}
boosting 查询中指定了抑制因子为 0.2,publish_time 的值在 2015-01-01 之后的文档得分不变,publish_time 的值在 2015-01-01 之前的文档得分为原得分的 0.2 倍。
constant_score query
constant_score query 包装一个 filter query,并返回匹配过滤器查询条件的文档,且它们的相关性评分都等于 boost 参数值(可以理解为原有的基于 tf-idf 或 bm25 的相关分固定为 1.0,所以最终评分为 1.0 * boost,即等于 boost 参数值)。下面的查询语句会返回 title 字段中含有关键词 elasticsearch 的文档,所有文档的评分都是 1.8:
GET books/_search
{
“query”: {
“constant_score”: {
“filter”: {
“term”: {
“title”: “elasticsearch”
}
},
“boost”: 1.8
}
}
}
dis_max query
dis_max query 与 bool query 有一定联系也有一定区别,dis_max query 支持多并发查询,可返回与任意查询条件子句匹配的任何文档类型。与 bool 查询可以将所有匹配查询的分数相结合使用的方式不同,dis_max 查询只使用最佳匹配查询条件的分数。请看下面的例子:
GET books/_search
{
“query”: {
“dis_max”: {
“tie_breaker”: 0.7,
“boost”: 1.2,
“queries”: [{
“term”: {
“age”: 34
}
},
{
“term”: {
“age”: 35
}
}
]
}
}
}
function_score query
function_score query 可以修改查询的文档得分,这个查询在有些情况下非常有用,比如通过评分函数计算文档得分代价较高,可以改用过滤器加自定义评分函数的方式来取代传统的评分方式。
使用 function_score query,用户需要定义一个查询和一至多个评分函数,评分函数会对查询到的每个文档分别计算得分。
下面这条查询语句会返回 books 索引中的所有文档,文档的最大得分为 5,每个文档的得分随机生成,权重的计算模式为相乘模式。
GET books/_search
{
“query”: {
“function_score”: {
“query”: {
“match all”: {}
},
“boost”: “5”,
“random_score”: {},
“boost_mode”: “multiply”
}
}
}
使用脚本自定义评分公式,这里把 price 值的十分之一开方作为每个文档的得分,查询语句如下:
GET books/_search
{
“query”: {
“function_score”: {
“query”: {
“match”: {
“title”: “java”
}
},
“script_score”: {
“inline”: “Math.sqrt(doc[‘price’].value/10)”
}
}
}
}
关于 function_score 的更多详细内容请查看 Elasticsearch function_score 查询最强详解。
indices query
indices query 适用于需要在多个索引之间进行查询的场景,它允许指定一个索引名字列表和内部查询。indices query 中有 query 和 no_match_query 两部分,query 中用于搜索指定索引列表中的文档,no_match_query 中的查询条件用于搜索指定索引列表之外的文档。下面的查询语句实现了搜索索引 books、books2 中 title 字段包含关键字 javascript,其他索引中 title 字段包含 basketball 的文档,查询语句如下:
GET books/_search
{
“query”: {
“indices”: {
“indices”: [“books”, “books2”],
“query”: {
“match”: {
“title”: “javascript”
}
},
“no_match_query”: {
“term”: {
“title”: “basketball”
}
}
}
}
}
嵌套查询
在 Elasticsearch 这样的分布式系统中执行全 SQL 风格的连接查询代价昂贵,是不可行的。相应地,为了实现水平规模地扩展,Elasticsearch 提供了以下两种形式的 join:
nested query(嵌套查询)
文档中可能包含嵌套类型的字段,这些字段用来索引一些数组对象,每个对象都可以作为一条独立的文档被查询出来。
has_child query(有子查询)和 has_parent query(有父查询)
父子关系可以存在单个的索引的两个类型的文档之间。has_child 查询将返回其子文档能满足特定查询的父文档,而 has_parent 则返回其父文档能满足特定查询的子文档。
nested query
文档中可能包含嵌套类型的字段,这些字段用来索引一些数组对象,每个对象都可以作为一条独立的文档被查询出来(用嵌套查询)。
PUT /my_index
{
“mappings”: {
“type1”: {
“properties”: {
“obj1”: {
“type”: “nested”
}
}
}
}
}
has_child query
文档的父子关系创建索引时在映射中声明,这里以员工(employee)和工作城市(branch)为例,它们属于不同的类型,相当于数据库中的两张表,如果想把员工和他们工作的城市关联起来,需要告诉 Elasticsearch 文档之间的父子关系,这里 employee 是 child type,branch 是 parent type,在映射中声明,执行命令:
PUT /company
{
“mappings”: {
“branch”: {},
“employee”: {
“parent”: { “type”: “branch” }
}
}
}
使用 bulk api 索引 branch 类型下的文档,命令如下:
POST company/branch/_bulk
{ “index”: { “_id”: “london” }}
{ “name”: “London Westminster”,”city”: “London”,”country”: “UK” }
{ “index”: { “_id”: “liverpool” }}
{ “name”: “Liverpool Central”,”city”: “Liverpool”,”country”: “UK” }
{ “index”: { “_id”: “paris” }}
{ “name”: “Champs Elysees”,”city”: “Paris”,”country”: “France” }
添加员工数据:
POST company/employee/_bulk
{ “index”: { “_id”: 1,”parent”:”london” }}
{ “name”: “Alice Smith”,”dob”: “1970-10-24”,”hobby”: “hiking” }
{ “index”: { “_id”: 2,”parent”:”london” }}
{ “name”: “Mark Tomas”,”dob”: “1982-05-16”,”hobby”: “diving” }
{ “index”: { “_id”: 3,”parent”:”liverpool” }}
{ “name”: “Barry Smith”,”dob”: “1979-04-01”,”hobby”: “hiking” }
{ “index”: { “_id”: 4,”parent”:”paris” }}
{ “name”: “Adrien Grand”,”dob”: “1987-05-11”,”hobby”: “horses” }
通过子文档查询父文档要使用 has_child 查询。例如,搜索 1980 年以后出生的员工所在的分支机构,employee 中 1980 年以后出生的有 Mark Thomas 和 Adrien Grand,他们分别在 london 和 paris,执行以下查询命令进行验证:
GET company/branch/_search
{
“query”: {
“has_child”: {
“type”: “employee”,
“query”: {
“range”: { “dob”: { “gte”: “1980-01-01” } }
}
}
}
}
搜索哪些机构中有名为 “Alice Smith” 的员工,因为使用 match 查询,会解析为 “Alice” 和 “Smith”,所以 Alice Smith 和 Barry Smith 所在的机构会被匹配,执行以下查询命令进行验证:
GET company/branch/_search
{
“query”: {
“has_child”: {
“type”: “employee”,
“score_mode”: “max”,
“query”: {
“match”: { “name”: “Alice Smith” }
}
}
}
}
可以使用 min_children 指定子文档的最小个数。例如,搜索最少含有两个 employee 的机构,查询命令如下:
GET company/branch/_search?pretty
{
“query”: {
“has_child”: {
“type”: “employee”,
“min_children”: 2,
“query”: {
“match_all”: {}
}
}
}
}
has_parent query
通过父文档查询子文档使用 has_parent 查询。比如,搜索哪些 employee 工作在 UK,查询命令如下:
GET company/employee/_search
{
“query”: {
“has_parent”: {
“parent_type”: “branch”,
“query”: {
“match”: { “country”: “UK }
}
}
}
}
地理位置查询
Elasticsearch 可以对地理位置点 geo_point 类型和地理位置形状 geo_shape 类型的数据进行搜索。为了学习方便,这里准备一些城市的地理坐标作为测试数据,每一条文档都包含城市名称和地理坐标这两个字段,这里的坐标点取的是各个城市中心的一个位置。首先把下面的内容保存到 geo.json 文件中:
{“index”:{ “_index”:”geo”,”_type”:”city”,”_id”:”1” }}
{“name”:”北京”,”location”:”39.9088145109,116.3973999023”}
{“index”:{ “_index”:”geo”,”_type”:”city”,”_id”: “2” }}
{“name”:”乌鲁木齐”,”location”:”43.8266300000,87.6168800000”}
{“index”:{ “_index”:”geo”,”_type”:”city”,”_id”:”3” }}
{“name”:”西安”,”location”:”34.3412700000,108.9398400000”}
{“index”:{ “_index”:”geo”,”_type”:”city”,”_id”:”4” }}
{“name”:”郑州”,”location”:”34.7447157466,113.6587142944”}
{“index”:{ “_index”:”geo”,”_type”:”city”,”_id”:”5” }}
{“name”:”杭州”,”location”:”30.2294080260,120.1492309570”}
{“index”:{ “_index”:”geo”,”_type”:”city”,”_id”:”6” }}
{“name”:”济南”,”location”:”36.6518400000,117.1200900000”}
创建一个索引并设置映射:
PUT geo
{
“mappings”: {
“city”: {
“properties”: {
“name”: {
“type”: “keyword”
},
“location”: {
“type”: “geo_point”
}
}
}
}
}
然后执行批量导入命令:
curl -XPOST “http://localhost:9200/_bulk?pretty“ –data-binary @geo.json
geo_distance query
geo_distance query 可以查找在一个中心点指定范围内的地理点文档。例如,查找距离天津 200km 以内的城市,搜索结果中会返回北京,命令如下:
GET geo/_search
{
“query”: {
“bool”: {
“must”: {
“match_all”: {}
},
“filter”: {
“geo_distance”: {
“distance”: “200km”,
“location”: {
“lat”: 39.0851000000,
“lon”: 117.1993700000
}
}
}
}
}
}
按各城市离北京的距离排序:
GET geo/_search
{
“query”: {
“match_all”: {}
},
“sort”: [{
“_geo_distance”: {
“location”: “39.9088145109,116.3973999023”,
“unit”: “km”,
“order”: “asc”,
“distance_type”: “plane”
}
}]
}
其中 location 对应的经纬度字段;unit 为 km 表示将距离以 km 为单位写入到每个返回结果的 sort 键中;distance_type 为 plane 表示使用快速但精度略差的 plane 计算方式。
geo_bounding_box query
geo_bounding_box query 用于查找落入指定的矩形内的地理坐标。查询中由两个点确定一个矩形,然后在矩形区域内查询匹配的文档。
GET geo/_search
{
“query”: {
“bool”: {
“must”: {
“match_all”: {}
},
“filter”: {
“geo_bounding_box”: {
“location”: {
“top_left”: {
“lat”: 38.4864400000,
“lon”: 106.2324800000
},
“bottom_right”: {
“lat”: 28.6820200000,
“lon”: 115.8579400000
}
}
}
}
}
}
}
geo_polygon query
geo_polygon query 用于查找在指定多边形内的地理点。例如,呼和浩特、重庆、上海三地组成一个三角形,查询位置在该三角形区域内的城市,命令如下:
GET geo/_search
{
“query”: {
“bool”: {
“must”: {
“match_all”: {}
}
},
“filter”: {
“geo_polygon”: {
“location”: {
“points”: [{
“lat”: 40.8414900000,
“lon”: 111.7519900000
}, {
“lat”: 29.5647100000,
“lon”: 106.5507300000
}, {
“lat”: 31.2303700000,
“lon”: 121.4737000000
}]
}
}
}
}
}
geo_shape query
geo_shape query 用于查询 geo_shape 类型的地理数据,地理形状之间的关系有相交、包含、不相交三种。创建一个新的索引用于测试,其中 location 字段的类型设为 geo_shape 类型。
PUT geoshape
{
“mappings”: {
“city”: {
“properties”: {
“name”: {
“type”: “keyword”
},
“location”: {
“type”: “geo_shape”
}
}
}
}
}
关于经纬度的顺序这里做一个说明,geo_point 类型的字段纬度在前经度在后,但是对于 geo_shape 类型中的点,是经度在前纬度在后,这一点需要特别注意。
把西安和郑州连成的线写入索引:
POST geoshape/city/1
{
“name”: “西安-郑州”,
“location”: {
“type”: “linestring”,
“coordinates”: [
[108.9398400000, 34.3412700000],
[113.6587142944, 34.7447157466]
]
}
}
查询包含在由银川和南昌作为对角线上的点组成的矩形的地理形状,由于西安和郑州组成的直线落在该矩形区域内,因此可以被查询到。命令如下:
GET geoshape/_search
{
“query”: {
“bool”: {
“must”: {
“match_all”: {}
},
“filter”: {
“geo_shape”: {
“location”: {
“shape”: {
“type”: “envelope”,
“coordinates”: [
[106.23248, 38.48644],
[115.85794, 28.68202]
]
},
“relation”: “within”
}
}
}
}
}
}
特殊查询
more_like_this query
more_like_this query 可以查询和提供文本类似的文档,通常用于近似文本的推荐等场景。查询命令如下:
GET books/search
{
“query”: {
“more_like this”: {
“fields”: [“title”, “description”],
“like”: “java virtual machine”,
“min_term_freq”: 1,
“max_query_terms”: 12
}
}
}
可选的参数及取值说明如下:
fields 要匹配的字段,默认是 _all 字段。
like 要匹配的文本。
min_term_freq 文档中词项的最低频率,默认是 2,低于此频率的文档会被忽略。
max_query_terms query 中能包含的最大词项数目,默认为 25。
min_doc_freq 最小的文档频率,默认为 5。
max_doc_freq 最大文档频率。
min_word length 单词的最小长度。
max_word length 单词的最大长度。
stop_words 停用词列表。
analyzer 分词器。
minimum_should_match 文档应匹配的最小词项数,默认为 query 分词后词项数的 30%。
boost terms 词项的权重。
include 是否把输入文档作为结果返回。
boost 整个 query 的权重,默认为 1.0。
script query
Elasticsearch 支持使用脚本进行查询。例如,查询价格大于 180 的文档,命令如下:
GET books/_search
{
“query”: {
“script”: {
“script”: {
“inline”: “doc[‘price’].value > 180”,
“lang”: “painless”
}
}
}
}
percolate query
一般情况下,我们是先把文档写入到 Elasticsearch 中,通过查询语句对文档进行搜索。percolate query 则是反其道而行之的做法,它会先注册查询条件,根据文档来查询 query。例如,在 my-index 索引中有一个 laptop 类型,文档有 price 和 name 两个字段,在映射中声明一个 percolator 类型的 query,命令如下:
PUT my-index
{
“mappings”: {
“laptop”: {
“properties”: {
“price”: { “type”: “long” },
“name”: { “type”: “text” }
},
“queries”: {
“properties”: {
“query”: { “type”: “percolator” }
}
}
}
}
}
注册一个 bool query,bool query 中包含一个 range query,要求 price 字段的取值小于等于 10000,并且 name 字段中含有关键词 macbook:
PUT /my-index/queries/1?refresh
{
“query”: {
“bool”: {
“must”: [{
“range”: { “price”: { “lte”: 10000 } }
}, {
“match”: { “name”: “macbook” }
}]
}
}
}
通过文档查询 query:
GET /my-index/_search
{
“query”: {
“percolate”: {
“field”: “query”,
“document_type”: “laptop”,
“document”: {
“price”: 9999,
“name”: “macbook pro on sale”
}
}
}
}
文档符合 query 中的条件,返回结果中可以查到上文中注册的 bool query。percolate query 的这种特性适用于数据分类、数据路由、事件监控和预警等场景。