2.3. 开始搜索
一旦你开始在 Elasticsearch 插入数据,你就可以通过_search
方式发送请求来进行搜索,如果使用匹配搜索功能,在请求体中使用Elasticsearch Query DSL
指定搜索条件。你也可以在请求头指定要搜索的索引名称。
如下图所示:搜索银行索引中,所有账号按照account_number
排序:
GET /bank/_search
{
"query": { "match_all": {} },
"sort": [
{ "account_number": "asc" }
]
}
默认情况下,会返回符合条件搜索的前10个文档:
{
"took" : 63,
"timed_out" : false,
"_shards" : {
"total" : 5,
"successful" : 5,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value": 1000,
"relation": "eq"
},
"max_score" : null,
"hits" : [ {
"_index" : "bank",
"_type" : "_doc",
"_id" : "0",
"sort": [0],
"_score" : null,
"_source" : {"account_number":0,"balance":16623,"firstname":"Bradshaw","lastname":"Mckenzie","age":29,"gender":"F","address":"244 Columbus Place","employer":"Euron","email":"bradshawmckenzie@euron.com","city":"Hobucken","state":"CO"}
}, {
"_index" : "bank",
"_type" : "_doc",
"_id" : "1",
"sort": [1],
"_score" : null,
"_source" : {"account_number":1,"balance":39225,"firstname":"Amber","lastname":"Duke","age":32,"gender":"M","address":"880 Holmes Lane","employer":"Pyrami","email":"amberduke@pyrami.com","city":"Brogan","state":"IL"}
}, ...
]
}
}
响应体里还提供了有关搜索请求的相关信息:
took
– 查询花费时长(毫秒)timed_out
– 请求是否超时_shards
– 搜索了多少分片,成功、失败或者跳过了多个分片(明细)max_score
– 最相关的文档分数hits.total.value
- 找到的文档总数hits.sort
- 文档排序方式 (如没有则按相关性分数排序)hits._score
- 文档的相关性算分 (match_all
没有算分)
每个搜索请求都是独立的:Elasticsearch 不维护任何请求中的状态信息。如果做分页的话,请在请求中指定 From 和 Size 参数。
如图所示:搜索第10到19的数据
GET /bank/_search
{
"query": { "match_all": {} },
"sort": [
{ "account_number": "asc" }
],
"from": 10,
"size": 10
}
现在你已经了解如何提交最基本的搜索请求了,则可以开始构建比 match_all 更有趣的查询了。
想搜索特定的字段,可以使用匹配查询。如下所示,请求搜索地址字段以查询地址中包含 mill 或 lane 的客户
GET /bank/_search
{
"query": { "match": { "address": "mill lane" } }
}
如果要全部匹配而不是仅仅是包含关键字之一,你需要使用match_phrase
而不是match
。(译者注:match
和 match_phrase
的区别就像是or
和and
的区别)如图所示:在请求中查询地址中同时包含mill
和lane
的客户:
GET /bank/_search
{
"query": { "match_phrase": { "address": "mill lane" } }
}
如果要构造更复杂的查询,可以使用布尔查询来组合多个查询条件,must match
、should match
、must not match
如图所示:请求在银行索引里搜索年龄是40的,但不居住在爱达荷州(ID)的客户:
GET /bank/_search
{
"query": {
"bool": {
"must": [
{ "match": { "age": "40" } }
],
"must_not": [
{ "match": { "state": "ID" } }
]
}
}
}
布尔查询中每个must
,should
,must_not
都被称为查询子句。每个must
或者should
查询子句中的条件都会影响文档的相关得分。得分越高,文档跟搜索条件匹配得越好。默认情况下,Elasticsearch 返回的文档会根据相关性算分倒序排列。
must_not
子句中认为是过滤条件。它会过滤返回结果,但不会影响文档的相关性算分,你还可以明确指定任意过滤条件去筛选结构化数据文档。
如图所示:请求搜索余额在20000 ~ 30000(包括30000) 之间的账户
GET /bank/_search
{
"query": {
"bool": {
"must": { "match_all": {} },
"filter": {
"range": {
"balance": {
"gte": 20000,
"lte": 30000
}
}
}
}
}
}
本译文仅用于学习和交流目的,转载请务必注明文章译者、出处、和本文链接
我们的翻译工作遵照 CC 协议,如果我们的工作有侵犯到您的权益,请及时联系我们。