十、ElasticSearch——搜索查询之一(URI Search,Request body Search、过滤,sort,折叠,分页,高亮,count,validate,explain,)

1 URI Search
1 ) 搜索API 端点地址
GET /twitter/_search?q=user:kimchy
GET /twitter/tweet,user/_search?q=user:kimchy 搜索多个mapping type
GET /kimchy,elasticsearch/_search?q=tag:wow 搜索多个索引
GET /_all/_search?q=tag:wow 查询所有
GET /_search?q=tag:wow 查询所有
搜索的端点地址可以是多索引多mapping type的。搜索的参数可作为URI请求参数给出,也可用 request body 给出。

URI 搜索方式通过URI参数来指定查询相关参数。让我们可以快速做一个查询。
GET /twitter/_search?q=user:kimchy
q=user:kimchy查询参数
可用的参数请参考:
https://www.elastic.co/guide/en/elasticsearch/reference/current/search-uri-request.html

2)URI中允许的参数是:
(1)q 查询字符串(映射到query_string查询,请参阅 查询字符串查询以获取更多详细信息)。
(2)df 在查询中未定义字段前缀时使用的默认字段。
(3)analyzer 分析查询字符串时要使用的分析器名称。
(4)analyze_wildcard 是否应该分析通配符和前缀查询。默认为false。
(5)batched_reduce_size 一次在协调节点上应该减少的分片结果的数量。如果请求中的潜在分片数量可能很大,则应将此值用作保护机制以减少每个搜索请求的内存开销。
(6)default_operator 要使用的默认运算符可以是AND或 OR。默认为OR。
(7)lenient 如果设置为true,则会导致基于格式的失败(如向数字字段提供文本)被忽略。默认为false。
(8)explain 对于每个命中,包含如何计算命中得分的解释。
(9)_source 设置为false禁用检索_source字段。您也可以使用_source_include&获取部分文档_source_exclude(请参阅请求主体 文档以获取更多详细信息)
(10)stored_fields 选择性存储的文件字段为每个命中返回,逗号分隔。没有指定任何值将导致没有字段返回。
(11)sort 排序以执行。可以是fieldName,或者是 fieldName:asc的形式fieldName:desc。fieldName可以是文档中的实际字段,也可以是_score根据分数表示排序的特殊名称。可以有几个sort参数(顺序很重要)。
(12)track_scores 排序时,设置为true仍然可以跟踪分数并将它们作为每次击中的一部分返回。
(13)timeout 搜索超时,限制在指定时间值内执行的搜索请求,并在到期时积累至该点的保留时间。默认没有超时。
(14)terminate_after 为每个分片收集的文档的最大数量,一旦达到该数量,查询执行将提前终止。如果设置,则响应将有一个布尔型字段terminated_early来指示查询执行是否实际已经terminate_early。缺省为no terminate_after。
(15)==from ==从命中的索引开始返回。默认为0。
(16)size 要返回的点击次数。默认为10。
(17)search_type 要执行的搜索操作的类型。可以是 dfs_query_then_fetch或(18)query_then_fetch。默认为query_then_fetch。有关可以执行的不同搜索类型的更多详细信息,请参阅 搜索类型。

3)查询结果说明
在这里插入图片描述
4)特殊的查询参数用法

如果只想知道有多少文档匹配某个查询(count),可以这样用参数:
GET /bank/_search?q=city:b*&size=0
如果只想知道有没有文档匹配某个查询(exist),可以这样用参数:
GET /bank/_search?q=city:b*&size=0&terminate_after=1
比较两个查询的结果,有什么区别。

2 Request body Search
Request body 搜索方式以JSON格式在请求体中定义查询 query。==请求方式可以是 GET 、POST 。 ==

GET /twitter/_search
{
“query” : {
“term” : { “user” : “kimchy” }
}
}

1 ) 可用的参数:
timeout:请求超时时长,限定在指定时长内响应(即使没查完);
from: 分页的起始行,默认0;
size:分页大小;
request_cache:是否缓存请求结果,默认true。
terminate_after:限定每个分片取几个文档。如果设置,则响应将有一个布尔型字段terminated_early来指示查询执行是否实际已经terminate_early。缺省为no terminate_after;
search_type:查询的执行方式,可选值dfs_query_then_fetch or query_then_fetch ,默认: query_then_fetch ;
batched_reduce_size:一次在协调节点上应该减少的分片结果的数量。如果请求中的潜在分片数量可能很大,则应将此值用作保护机制以减少每个搜索请求的内存开销。

2 ) query 元素定义查询 query 元素用Query DSL 来定义查询。

GET /_search
{
“query” : {
“term” : { “user” : “kimchy” }
}
}

3 ) 指定返回哪些内容
(1) source filter 对_source字段进行选择

GET /_search
{
“_source”: false,
“query” : {
“term” : { “user” : “kimchy” }
}
}

GET /_search
{
“_source”: [ “obj1.", "obj2.” ],
“query” : {
“term” : { “user” : “kimchy” }
}
}

GET /_search
{
“_source”: “obj.*”,
“query” : {
“term” : { “user” : “kimchy” }
}
}

GET /_search
{
“_source”: {
“includes”: [ “obj1.", "obj2.” ],
“excludes”: [ “*.description” ]
},
“query” : {
“term” : { “user” : “kimchy” }
}
}

(2) stored_fields来指定返回哪些stored字段

GET /_search
{
“stored_fields” : [“user”, “postDate”],
“query” : {
“term” : { “user” : “kimchy” }
}
}

  • 可用来指定返回所有存储字段

(3) docValue Field 返回存储了docValue的字段值

GET /_search
{
“query” : {
“match_all”: {}
},
“docvalue_fields” : [“test1”, “test2”]
}

(4) version 来指定返回文档的版本字段

GET /_search
{
“version”: true,
“query” : {
“term” : { “user” : “kimchy” }
}
}

(5) explain 返回文档的评分解释

GET /_search
{
“explain”: true,
“query” : {
“term” : { “user” : “kimchy” }
}
}

(6) Script Field 用脚本来对命中的每个文档的字段进行运算后返回

GET /bank/_search
{
“query”: {
“match_all”: {}
},
“script_fields”: {
“test1”: {
“script”: {
“lang”: “painless”,
“source”: “doc[‘balance’].value * 2” doc指文档

  }
},
"test2": {
  "script": {
    "lang": "painless",
    "source": "doc['age'].value * params.factor",
    "params": {
      "factor": 2
    }
  }
} }}

GET /bank/_search
{
“query”: {
“match_all”: {}
},
“script_fields”: {
“ffx”: {
“script”: {
“lang”: “painless”,
“source”: “doc[‘age’].value * doc[‘balance’].value”
}
},
“balance2": {
“script”: {
“lang”: “painless”,
“source”: "params[’_source’].balance
2” params _source 取 _source字段值

  }
}

}
}
官方推荐使用doc,理由是用doc效率比取_source 高。

3 过滤
1)min_score 限制最低评分得分。

GET /_search
{
“min_score”: 0.5,
“query” : {
“term” : { “user” : “kimchy” }
}
}

2)post_filter 后置过滤:在查询命中文档、完成聚合后,再对命中的文档进行过滤。
如:要在一次查询中查询品牌为gucci且颜色为红色的shirts,同时还要得到gucci品牌各颜色的shirts的分面统计。

PUT /shirts
{
“mappings”: {
“_doc”: {
“properties”: {
“brand”: { “type”: “keyword”},
“color”: { “type”: “keyword”},
“model”: { “type”: “keyword”}
}
}
}
}

PUT /shirts/_doc/1?refresh
{
“brand”: “gucci”,
“color”: “red”,
“model”: “slim”
}
PUT /shirts/_doc/2?refresh
{
“brand”: “gucci”,
“color”: “green”,
“model”: “seec”
}

GET /shirts/_search
{
“query”: {
“bool”: {
“filter”: {
“term”: { “brand”: “gucci” }
}
}
},
“aggs”: {
“colors”: {
“terms”: { “field”: “color” }
}
},
“post_filter”: {
“term”: { “color”: “red” }
}
}

4 sort 排序

可以指定按一个或多个字段排序。也可通过_score指定按评分值排序,_doc 按索引顺序排序。默认是按相关性评分从高到低排序。

GET /bank/_search
{
“query”: {
“match_all”: {}
},
“sort”: [
{
“age”: {
“order”: “desc”
} },
{
“balance”: {
“order”: “asc”
} },
“_score”
]
}
order 值:asc、desc。如果不给定,默认是asc,_score默认是desc
返回结果
“hits”: {
“total”: 1000,
“max_score”: null,
“hits”: [
{
“_index”: “bank”,
“_type”: “_doc”,
“_id”: “549”,
“_score”: 1,
“_source”: {
“account_number”: 549,
“balance”: 1932, “age”: 40, “state”: “OR”
},
“sort”: [ 结果中每个文档会有排序字段值给出
40,
1932,
1
] }

1)多值字段排序(按照多值的min,max,sum,avg,mrdain来排序)
对于值是数组或多值的字段,也可进行排序,通过mode参数指定按多值的:
在这里插入图片描述

PUT /my_index/_doc/1?refresh
{
“product”: “chocolate”,
“price”: [20, 4]
}

POST /_search
{
“query” : {
“term” : { “product” : “chocolate” }
},
“sort” : [
{“price” : {“order” : “asc”, “mode” : “avg”}}
]
}

2)Missing values 缺失该字段的文档排序(missing 的值可以是 _last, _first

GET /_search
{
“sort” : [
{ “price” : {“missing” : “_last”} }
],
“query” : {
“term” : { “product” : “chocolate” }
}
}

3)地理空间距离排序

_geo_distance 距离排序关键字
pin.location是 geo_point 类型的字段
distance_type:距离计算方式 arc球面 、plane 平面。
unit: 距离单位 km 、m 默认m

https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-sort.html#geo-sorting

GET /_search
{
“sort” : [
{
“_geo_distance” : {
“pin.location” : [-70, 40],
“order” : “asc”,
“unit” : “km”,
“mode” : “min”,
“distance_type” : “arc”
}
}
],
“query” : {
“term” : { “user” : “kimchy” }
}
}

4)Script Based Sorting 基于脚本计算的排序

GET /_search
{
“query” : {
“term” : { “user” : “kimchy” }
},
“sort” : {
“_script” : {
“type” : “number”,
“script” : {
“lang”: “painless”,
“source”: “doc[‘field_name’].value * params.factor”,
“params” : {
“factor” : 1.1
}
},
“order” : “asc”
}
}
}

5 折叠
1)用 collapse指定根据某个字段对命中结果进行折叠(先按字段分组,然后取出1条作为代表)

GET /bank/_search
{
“query”: {
“match_all”: {}
},
“collapse” : {
“field” : “age”
},
“sort”: [“balance”]
}

在这里插入图片描述

2)在inner_hits 中返回多个角度的组内topN(多个角度的结果同时返回)

GET /twitter/_search
{
“query”: {
“match”: {
“message”: “elasticsearch”
}
},
“collapse” : {
“field” : “user”,
“inner_hits”: [
{
“name”: “most_liked”,
“size”: 3,
“sort”: [“likes”]
},
{
“name”: “most_recent”,
“size”: 3,
“sort”: [{ “date”: “asc” }]
}
]
},
“sort”: [“likes”]
}

6 分页
1)from and size

GET /_search
{
“from” : 0, “size” : 10,
“query” : {
“term” : { “user” : “kimchy” }
}
}

注意:搜索请求耗用的堆内存和时间与 from + size 大小成正比。分页越深耗用越大,为了不因分页导致OOM或严重影响性能,ES中规定from + size 不能大于索引setting参数 index.max_result_window 的值,默认值为 10,000。

需要深度分页, 不受index.max_result_window 限制,怎么办?

2)Search after 在指定文档后取文档, 可用于深度分页

在这里插入图片描述
注意:使用search_after,要求查询必须指定排序
并且这个排序组合值每个文档唯一(最好排序中包含_id字段)search_after的值用的就是这个排序值。
用search_after时 from 只能为0、-1。

7 高亮
在这里插入图片描述

在这里插入图片描述
文档
https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-highlighting.html
高亮相关问题思路
高亮是什么:文本加了标签
如何对一个字符串中的特定子串实现高亮:替换它
在搜索引擎中如何高效做高亮:知道了分词的position可以直接插入标签
offset在哪里有

8 Profile 调试、优化
对于执行缓慢的查询,我们很想知道它为什么慢,时间都耗在哪了,可以在查询上加入上 profile 来获得详细的执行步骤、耗时信息

GET /twitter/_search
{
“profile”: true,
“query” : {
“match” : { “message” : “some number” }
}
}
https://www.elastic.co/guide/en/elasticsearch/reference/current/search-profile.html

9 count api 查询数量

PUT /twitter/_doc/1?refresh
{
“user”: “kimchy”
}

GET /twitter/_doc/_count?q=user:kimchy

GET /twitter/_doc/_count
{
“query” : {
“term” : { “user” : “kimchy” }
}
}

{
“count” : 1,
“_shards” : {
“total” : 5,
“successful” : 5,
“skipped” : 0,
“failed” : 0
}
}

10 validate api 检查
用来检查我们的查询是否正确,以及查看底层生成查询是怎样的
GET twitter/_validate/query?q=user:foo

校验查询
GET twitter/_doc/_validate/query
{
“query”: {
“query_string”: {
“query”: “post_date:foo”,
“lenient”: false
}
}
}

获得查询解释
GET twitter/_doc/_validate/query?explain=true
{
“query”: {
“query_string”: {
“query”: “post_date:foo”,
“lenient”: false
}
}
}

在这里插入图片描述
11 Explain api

获得某个查询的评分解释,及某个文档是否被这个查询命中
GET /twitter/_doc/0/_explain
{
“query” : {
“match” : { “message” : “elasticsearch” }
}
}

https://www.elastic.co/guide/en/elasticsearch/reference/current/search-explain.html

12 Search Shards API
让我们可以了解可执行查询的索引分片节点情况
GET /twitter/_search_shards
想知道指定routing值的查询将在哪些分片节点上执行
GET /twitter/_search_shards?routing=foo,baz

13 Search Template

在这里插入图片描述
https://www.elastic.co/guide/en/elasticsearch/reference/current/search-template.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值