星语课程网
Elasticsearch(es) 查询语句语法详解
来源:本站编辑
2023-11-25 17:55
12
[Elasticsearch(es) 查询语句语法详解](https://www.cnblogs.com/Gaimo/p/16036853.html) =========================================================================== Elasticsearch 查询语句采用基于 RESTful 风格的接口封装成 JSON 格式的对象,称之为 Query DSL。Elasticsearch 查询分类大致分为**全文查询**、**词项查询**、**复合查询**、**嵌套查询**、**位置查询**、**特殊查询**。 Elasticsearch 查询从机制分为两种,一种是根据用户输入的查询词,通过排序模型计算文档与查询词之间的**相关度**,并根据评分高低排序返回;另一种是**过滤机制**,只根据过滤条件对文档进行过滤,不计算评分,速度相对较快。 全文查询 ---- es 全文查询主要用于在全文字段上,主要考虑查询词与文档的相关性(Relevance)。 ### match query match query **用于搜索单个字段**,首先会针对查询语句进行解析(经过 analyzer),主要是对查询语句进行分词,分词后查询语句的任何一个词项被匹配,文档就会被搜到,默认情况下相当于对分词后词项进行 or 匹配操作。 ```json GET article/\_search { "query": { "match": { "title": { "query": "Elasticsearch 查询优化" } } } } ``` 等同于 or 匹配操作,如下: ```json GET article/\_search { "query": { "match": { "title": { "query": "Elasticsearch 查询优化", "operator": "or" } } } } ``` 如果想查询匹配所有关键词的文档,可以用 and 操作符连接,如下: ```json GET article/\_search { "query": { "match": { "title": { "query": "Elasticsearch 查询优化", "operator": "and" } } } } ``` ### match\_phrase query match\_phrase query 首先会把 query 内容分词,分词器可以自定义,同时文档还要满足以下两个条件才会被搜索到: 1. **分词后所有词项都要出现在该字段中(相当于 and 操作)**。 2. **字段中的词项顺序要一致**。 例如,有以下 3 个文档,使用 match\_phrase 查询 “what a wonderful life”,只有前两个文档会被匹配: ```json 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 query 查询](https://www.knowledgedict.com/tutorial/elasticsearch-query-match-phrase.html)。 ### match\_phrase\_prefix query match\_phrase\_prefix 和 match\_phrase 类似,只不过 match\_phrase\_prefix 支持最后一个 term 的前缀匹配。 ```json GET test\_idx/test\_tp/\_search { "query": { "match\_phrase\_prefix": { "desc": "what li" } } } ``` ### multi\_match query multi\_match 是 match 的升级,**用于搜索多个字段**。查询语句为 “java 编程”,查询域为 title 和 description,查询语句如下: ```json GET books/\_search { "query": { "multi\_match": { "query": "java 编程", "fields": \["title", "description"\] } } } ``` multi\_match 支持对要搜索的**字段的名称使用通配符**,示例如下: ```json GET books/\_search { "query": { "multi\_match": { "query": "java 编程", "fields": \["title", "\*\_name"\] } } } ``` 同时,也可以用**指数符指定搜索字段的权重**。指定关键词出现在 title 中的权重是出现在 description 字段中的 3 倍,命令如下: ```json GET books/\_search { "query": { "multi\_match": { "query": "java 编程", "fields": \["title^3", "description"\] } } } ``` 更多详细内容在 [elasticsearch 的 multi\_match 查询](https://www.knowledgedict.com/tutorial/elasticsearch-query-multi-match.html)。 ### common\_terms query common\_terms query 是一种在不牺牲性能的情况下替代停用词提高搜索准确率和召回率的方案。 查询中的每个词项都有一定的代价,以搜索 “The brown fox” 为例,query 会被解析成三个词项 “the”“brown” 和“fox”,每个词项都会到索引中执行一次查询。很显然包含 “the” 的文档非常多,相比其他词项,“the”的重要性会低很多。传统的解决方案是把 “the” 当作停用词处理,去除停用词之后可以减少索引大小,同时在搜索时减少对停用词的收缩。 虽然停用词对文档评分影响不大,但是当停用词仍然有重要意义的时候,去除停用词就不是完美的解决方案了。如果去除停用词,就无法区分 “happy” 和“not happy”, “The”“To be or not to be”就不会在索引中存在,搜索的准确率和召回率就会降低。 common\_terms query 提供了一种解决方案,它把 query 分词后的词项分成重要词项(低频词项)和不重要的词项(高频词,也就是之前的停用词)。在搜索的时候,首先搜索和重要词项匹配的文档,这些文档是词项出现较少并且词项对其评分影响较大的文档。然后执行第二次查询,搜索对评分影响较小的高频词项,但是不计算所有文档的评分,而是只计算第一次查询已经匹配的文档得分。如果一个查询中只包含高频词,那么会通过 and 连接符执行一个单独的查询,换言之,会搜索所有的词项。 词项是高频词还是低频词是通过 cutoff frequency 来设置阀值的,取值可以是绝对频率(频率大于 1)或者相对频率(0~1)。common\_terms query 最有趣之处在于它能自适应特定领域的停用词,例如,在视频托管网站上,诸如 “clip” 或“video”之类的高频词项将自动表现为停用词,无须保留手动列表。 例如,文档频率高于 0.1% 的词项将会被当作高频词项,词频之间可以用 low\_freq\_operator、high\_freq\_operator 参数连接。设置低频词操作符为 “and” 使所有的低频词都是必须搜索的,示例代码如下: ```json GET books/\_search { "query": { "common": { "body": { "query": "nelly the elephant as a cartoon", "cutoff\_frequency": 0.001, "low\_freq\_operator": "and" } } } } ``` 上述操作等价于: ```json GET books/\_search { "query": { "bool": { "must": \[ { "term": { "body": "nelly" } }, { "term": { "body": "elephant" } }, { "term": { "body": "cartoon" } } \], "should": \[ { "term": { "body": "the" } }, { "term": { "body": "as" } }, { "term": { "body": "a" } } \] } } } ``` ### query\_string query query\_string query 是与 Lucene 查询语句的语法结合非常紧密的一种查询,允许在一个查询语句中使用多个特殊条件关键字(如:AND | OR | NOT)对多个字段进行查询,建议熟悉 Lucene 查询语法的用户去使用。 ### simple\_query\_string simple\_query\_string 是一种适合直接暴露给用户,并且具有非常完善的查询语法的查询语句,接受 Lucene 查询语法,解析过程中发生错误不会抛出异常。例子如下: ```json GET books/\_search { "query": { "simple\_query\_string": { "query": "\\"fried eggs\\" +(eggplant | potato) -frittata", "analyzer": "snowball", "fields": \["body^5", "\_all"\], "default\_operator": "and" } } } ``` 词项查询 ---- 全文查询在执行查询之前会分析查询字符串,词项查询时对倒排索引中存储的词项进行**精确匹配操作**。词项级别的查询通常用于结构化数据,如数字、日期和枚举类型。 ### term query term 查询用来查找指定字段中包含给定单词的文档,term 查询不被解析,只有查询词和文档中的词精确匹配才会被搜索到,应用场景为查询人名、地名等需要精准匹配的需求。比如,查询 title 字段中含有关键词 “思想” 的书籍,查询命令如下: ```json GET books/\_search { "query": { "term": { "title": "思想" } } } ``` 避免 term 查询对 text 字段使用查询。 默认情况下,Elasticsearch 针对 text 字段的值进行解析分词,这会使查找 text 字段值的精确匹配变得困难。 要搜索 text 字段值,需改用 match 查询。 ### terms query terms 查询是 term 查询的升级,可以用来查询文档中包含多个词的文档。比如,想查询 title 字段中包含关键词 “java” 或 “python” 的文档,构造查询语句如下: ```json { "query": { "terms": { "title": \["java", "python"\] } } } ``` ### range query range query 即范围查询,用于匹配在某一范围内的数值型、日期类型或者字符串型字段的文档,比如搜索哪些书籍的价格在 50 到 100 之间、哪些书籍的出版时间在 2015 年到 2019 年之间。**使用 range 查询只能查询一个字段,不能作用在多个字段上**。 range 查询支持的参数有以下几种: * gt 大于,查询范围的最小值,也就是下界,但是不包含临界值。 * gte 大于等于,和 gt 的区别在于包含临界值。 * lt 小于,查询范围的最大值,也就是上界,但是不包含临界值。 * lte 小于等于,和 lt 的区别在于包含临界值。 例如,想要查询价格大于 50,小于等于 70 的书籍,即 50 < price <= 70,构造查询语句如下: ```json GET bookes/\_search { "query": { "range": { "price": { "gt": 50, "lte": 70 } } } } ``` 查询出版日期在 2015 年 1 月 1 日和 2019 年 12 月 31 之间的书籍,对 publish\_time 字段进行范围查询,命令如下: ```json { "query": { "range": { "publish\_ time": { "gte": "2015-01-01", "lte": "2019-12-31", "format": "yyyy-MM-dd" } } } } ``` 有关 es 更详细的 range query 可以查看 [Elasticsearch(es)范围查询及 Lucene 底层原理实现](https://www.knowledgedict.com/tutorial/elasticsearch-query-range-query.html)。 ### exists query exists 查询会返回字段中至少有一个非空值的文档。 举例说明如下: ```json { "query": { "exists": { "field": "user" } } } ``` 以下文档会匹配上面的查询: * `{ "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 为前缀的关键词的文档,查询语句如下: ```json GET books/\_search { "query": { "prefix": { "description": "win" } } } ``` ### wildcard query wildcard query 中文译为通配符查询,支持单字符通配符和多字符通配符,`?` 用来匹配一个任意字符,`*` 用来匹配零个或者多个字符。 以 H?tland 为例,Hatland、Hbtland 等都可以匹配,但是不能匹配 Htland,`?` 只能代表一位。H\*tland 可以匹配 Htland、Habctland 等,`*` 可以代表 0 至多个字符。**和 prefix 查询一样,wildcard 查询的查询性能也不是很高,需要消耗较多的 CPU 资源。** 下面举一个 wildcard 查询的例子,假设需要找某一作者写的书,但是忘记了作者名字的全称,只记住了前两个字,那么就可以使用通配符查询,查询语句如下: ```json 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 开头紧跟着数字的邮政编码,使用正则表达式查询构造查询语句如下: ```json GET books/\_search { "query": { "regexp": { "postcode": "W\[0-9\].+" } } } ``` ### fuzzy query 编辑距离又称 Levenshtein 距离,是指两个字串之间,由一个转成另一个所需的最少编辑操作次数。许可的编辑操作包括将一个字符替换成另一个字符,插入一个字符,删除一个字符。fuzzy 查询就是通过计算词项与文档的编辑距离来得到结果的,但是使用 fuzzy 查询需要消耗的资源比较大,查询效率不高,适用于需要模糊查询的场景。举例如下,用户在输入查询关键词时不小心把 “javascript” 拼成 “javascritp”,在存在拼写错误的情况下使用模糊查询仍然可以搜索到含有 “javascript” 的文档,查询语句如下: ```json GET books/\_search { "query": { "fuzzy": { "title": "javascritp" } } } ``` ### type query type query 用于查询具有指定类型的文档。例如查询 Elasticsearch 中 type 为 computer 的文档,查询语句如下: ```json GET books/\_search { "query": { "type": { "value": "computer" } } } ``` ### ids query ids query 用于查询具有指定 id 的文档。类型是可选的,也可以省略,也可以接受一个数组。如果未指定任何类型,则会查询索引中的所有类型。例如,查询类型为 computer,id 为 1、3、5 的文档,**本质上是对文档 `_id` 的查询,所以对应的 value 是字符串类型**,查询语句如下: ```json GET books/\_search { "query": { "ids": { "type": "computer", "values": \["1", "3", "5"\] } } } ``` es 查询中如果要排除一些指定的 id 列表可以结合 ids query 和 bool 查询的 must\_not,具体参照 [Elasticsearch(es)不匹配或排除指定的 id 列表](https://www.knowledgedict.com/tutorial/elasticsearch-query-exclude-ids.html)。 复合查询 ---- 复合查询就是把一些简单查询组合在一起实现更复杂的查询需求,除此之外,复合查询还可以控制另外一个查询的行为。 ### 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 查询语句如下: ```json 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(组合查询)详解](https://www.knowledgedict.com/tutorial/elasticsearch-query-bool.html)。 ### boosting query boosting 查询用于需要对两个查询的评分进行调整的场景,boosting 查询会把两个查询封装在一起并降低其中一个查询的评分。 boosting 查询包括 positive、negative 和 negative\_boost 三个部分,positive 中的查询评分保持不变,negative 中的查询会降低文档评分,negative\_boost 指明 negative 中降低的权值。如果我们想对 2015 年之前出版的书降低评分,可以构造一个 boosting 查询,查询语句如下: ```json 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: ```json 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 查询只使用最佳匹配查询条件的分数。请看下面的例子: ```json 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,每个文档的得分随机生成,权重的计算模式为相乘模式。 ```json GET books/\_search { "query": { "function\_score": { "query": { "match all": {} }, "boost": "5", "random\_score": {}, "boost\_mode": "multiply" } } } ``` 使用脚本自定义评分公式,这里把 price 值的十分之一开方作为每个文档的得分,查询语句如下: ```json GET books/\_search { "query": { "function\_score": { "query": { "match": { "title": "java" } }, "script\_score": { "inline": "Math.sqrt(doc\['price'\].value/10)" } } } } ``` 关于 function\_score 的更多详细内容请查看 [Elasticsearch function\_score 查询最强详解](https://www.knowledgedict.com/tutorial/elasticsearch-function_score.html)。 ### indices query indices query 适用于需要在多个索引之间进行查询的场景,它允许指定一个索引名字列表和内部查询。indices query 中有 query 和 no\_match\_query 两部分,query 中用于搜索指定索引列表中的文档,no\_match\_query 中的查询条件用于搜索指定索引列表之外的文档。下面的查询语句实现了搜索索引 books、books2 中 title 字段包含关键字 javascript,其他索引中 title 字段包含 basketball 的文档,查询语句如下: ```json 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 文档中可能包含嵌套类型的字段,这些字段用来索引一些数组对象,每个对象都可以作为一条独立的文档被查询出来(用嵌套查询)。 ```json PUT /my\_index { "mappings": { "type1": { "properties": { "obj1": { "type": "nested" } } } } } ``` ### has\_child query 文档的父子关系创建索引时在映射中声明,这里以员工(employee)和工作城市(branch)为例,它们属于不同的类型,相当于数据库中的两张表,如果想把员工和他们工作的城市关联起来,需要告诉 Elasticsearch 文档之间的父子关系,这里 employee 是 child type,branch 是 parent type,在映射中声明,执行命令: ```json PUT /company { "mappings": { "branch": {}, "employee": { "parent": { "type": "branch" } } } } ``` 使用 bulk api 索引 branch 类型下的文档,命令如下: ```json 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" } ``` 添加员工数据: ```json 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,执行以下查询命令进行验证: ```json 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 所在的机构会被匹配,执行以下查询命令进行验证: ```json GET company/branch/\_search { "query": { "has\_child": { "type": "employee", "score\_mode": "max", "query": { "match": { "name": "Alice Smith" } } } } } ``` 可以使用 min\_children 指定子文档的最小个数。例如,搜索最少含有两个 employee 的机构,查询命令如下: ```json GET company/branch/\_search?pretty { "query": { "has\_child": { "type": "employee", "min\_children": 2, "query": { "match\_all": {} } } } } ``` ### has\_parent query 通过父文档查询子文档使用 has\_parent 查询。比如,搜索哪些 employee 工作在 UK,查询命令如下: ```json GET company/employee/\_search { "query": { "has\_parent": { "parent\_type": "branch", "query": { "match": { "country": "UK } } } } } ``` 位置查询 ---- Elasticsearch 可以对地理位置点 geo\_point 类型和地理位置形状 geo\_shape 类型的数据进行搜索。为了学习方便,这里准备一些城市的地理坐标作为测试数据,每一条文档都包含城市名称和地理坐标这两个字段,这里的坐标点取的是各个城市中心的一个位置。首先把下面的内容保存到 geo.json 文件中: ```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"} ``` 创建一个索引并设置映射: ```json PUT geo { "mappings": { "city": { "properties": { "name": { "type": "keyword" }, "location": { "type": "geo\_point" } } } } } ``` 然后执行批量导入命令: ```shell curl -XPOST "http://localhost:9200/\_bulk?pretty" --data-binary @geo.json ``` ### geo\_distance query geo\_distance query 可以查找在一个中心点指定范围内的地理点文档。例如,查找距离天津 200km 以内的城市,搜索结果中会返回北京,命令如下: ```json GET geo/\_search { "query": { "bool": { "must": { "match\_all": {} }, "filter": { "geo\_distance": { "distance": "200km", "location": { "lat": 39.0851000000, "lon": 117.1993700000 } } } } } } ``` 按各城市离北京的距离排序: ```json 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 用于查找落入指定的矩形内的地理坐标。查询中由两个点确定一个矩形,然后在矩形区域内查询匹配的文档。 ```json 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 用于查找在指定**多边形**内的地理点。例如,呼和浩特、重庆、上海三地组成一个三角形,查询位置在该三角形区域内的城市,命令如下: ```json 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 类型。 ```json PUT geoshape { "mappings": { "city": { "properties": { "name": { "type": "keyword" }, "location": { "type": "geo\_shape" } } } } } ``` 关于经纬度的顺序这里做一个说明,geo\_point 类型的字段纬度在前经度在后,但是对于 geo\_shape 类型中的点,是经度在前纬度在后,这一点需要特别注意。 把西安和郑州连成的线写入索引: ```json POST geoshape/city/1 { "name": "西安-郑州", "location": { "type": "linestring", "coordinates": \[ \[108.9398400000, 34.3412700000\], \[113.6587142944, 34.7447157466\] \] } } ``` 查询包含在由银川和南昌作为对角线上的点组成的矩形的地理形状,由于西安和郑州组成的直线落在该矩形区域内,因此可以被查询到。命令如下: ```json 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 可以查询和提供文本类似的文档,通常用于近似文本的推荐等场景。查询命令如下: ```json 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 的文档,命令如下: ```json 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,命令如下: ```json 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: ```json PUT /my-index/queries/1?refresh { "query": { "bool": { "must": \[{ "range": { "price": { "lte": 10000 } } }, { "match": { "name": "macbook" } }\] } } } ``` 通过文档查询 query: ```json GET /my-index/\_search { "query": { "percolate": { "field": "query", "document\_type": "laptop", "document": { "price": 9999, "name": "macbook pro on sale" } } } } ``` 文档符合 query 中的条件,返回结果中可以查到上文中注册的 bool query。percolate query 的这种特性适用于数据分类、数据路由、事件监控和预警等场景。
点赞
热门评论
最新评论
匿名用户
+1
-1
·
回复TA
暂无热门评论
相关推荐
阅读更多资讯
热门评论 最新评论
暂无热门评论