- 12
- 0
- 约9.15千字
- 约 12页
- 2021-11-10 发布于天津
- 举报
elasticsearch 搜索
搜索
检索单个文档
现在 Elasticsearch 中已经存储了一些数据,我们可以根据业务需求开始工作了。第一个需求 是能够检索单个员工的信息。
这对于 Elasticsearch来说非常简单。我们只要执行 HTTP GET请求并指出文档的“地址”— —索引、类型和 ID 既可。根据这三部分信息,我们就可以返回原始 JSON文档:
GET /megacorp/employee/1
响应的内容中包含一些文档的元信息, John Smith 的原始 JSON文档包含在 _source 字段中。
{
_index :
megacorp,
_type :
employee,
_id :
1,
_version
1,
found :
true,
_source : { first_name : John, last_name : Smith, age : 25,
about : I love to go rock climbing,
interests: [ sports, music ]
}
}
我们通过 HTTP 方法 GET来检索文档,同样的,我们可以使用 DELETE方法删除文档,使用
HEAD方法检查某文档是否存在。如果想更新已存在的文档,我们只需再 PUT一次。
搜索全部文档
我们尝试一个最简单的搜索全部员工的请求:
GET /megacorp/employee/_search
你可以看到我们依然使用 megacorp 索引和 employee 类型,但是我们在结尾使用关键字 _search 来取代原来的文档 ID。响应内容的 hits 数组中包含了我们所有的三个文档。默认情 况下搜索会返回前 10 个结果。
{
6,took:
6,
}
}
timed_out: false,
_shards: { ... },
hits: {
total:
3,
max_score: 1,
hits: [{
_index:
_type:
_id:
_score:
_source: {
first_name:
megacorp, employee, 3,
1,
Douglas,
Fir,
35,
I like to build cabinets,
interests: [ forestry ]
last_name:
age:
about:
}, {
index:
_type:
_id:
_score:
megacorp, employee, 1,
1,
_source: {
first_name:
last_name:
John,
Smith,
25,
I love to go rock climbing, interests: [ sports, music ]
age:
about:
}, {
index:
_type:
_id:
megacorp, employee, 2,
_score:
1,
_source: {
first_name:
last_name:
age:
about:
Jane,
Smith,
32,
I like to collect rock albums,
interests: [ music ]
}
}
响应内容不仅会告诉我们哪些文档被匹配到, 而且这些文档内容完整的被包含在其中—我们 在给用户展示搜索结果时需要用到的所有信息都有了。
搜索姓氏中包含 Smith 的员工
要做到这一点,我们将在命令行中使用轻量级的搜索方法。这种方法常被称作查询字符串 (query string) 搜索,因为我们像传递 URL 参数一样去传递查询语句:
GET /megacorp/employee/_search?q=last_name:Smith
我们在请求中依旧使用 _search 关键字,然后将查询语句传递给参数 q=。这样就可以得到所
有姓氏为 Smith 的结果:
{
hits: {
total: 2,
max_score: 0
hits: [
{
_source: {
first_name: John, last_name: Smith, age: 25,
about: I love to go rock climbing,
interests: [ sports, music ]
}
}, {
_source: {
first_name
Jane,
last_name:
Smith,
age:
32,
about:
I like to collect rock albums
interests: [
music ]
}
}
]
}
}
DSL语句查询
查询字符串搜索便于通过命令行完成特定 (ad hoc)的搜索,但是它也有局限性(参阅简单搜 索章节)。 El
原创力文档

文档评论(0)