上一篇,我們介紹了什么是 Elasticsearch,它能做什么用以及基本概念(索引 Index、文檔 Document、類型 Type)理解。這篇主要對 文檔的基本 CRUD 以及如何批量操作進行講解。下面讓我們進入正題。
一、文檔的 CRUE
Create 文檔
支持自動生成文檔 Id 和指定文檔 Id 兩種方法
#create document. 自動生成 Id
POST songs/_doc
{
"name":"說好不哭",
"author":"周傑倫",
"price":3
}
#create document. 指定Id。如果 Id 已經存在,報錯
PUT songs/_create/1
{
"name":"說好不哭",
"author":"周傑倫",
"price":3
}
Get 文檔
#找到文檔
Get songs/_doc/1
result:
{
"_index" : "songs",
"_type" : "_doc",
"_id" : "1",
"_version" : 1,
"_seq_no" : 0,
"_primary_term" : 1,
"found" : true,
"_source" : {
"name" : "說好不哭",
"author" : "周傑倫",
"price" : 3
}
}
- 找到文檔,返回 HTTP 200
- 文檔元信息
- _index/_type/,_type 在版本7中只有 _doc 類型
- _version 版本信息,同一個 Id 的文檔被刪除了,版本號也會增加
- _source 中默認包含文檔的原始信息
- 文檔元信息
- 找不到,返回 HTTP 404
Index 文檔
Index 也是用於創建文檔的方法,和 Create 不同有一些不同,如果文檔不存在情況,直接創建新文檔,否者刪除原來的文檔,新文檔被索引,_version 版本加一。
PUT songs/_doc/1
{
"name":"說好不哭",
"author":"周傑倫",
"price":0
}
result:
{
"_index" : "songs",
"_type" : "_doc",
"_id" : "1",
"_version" : 2,//+1
"result" : "updated",
"_shards" : {
"total" : 2,
"successful" : 2,
"failed" : 0
},
"_seq_no" : 1,
"_primary_term" : 1
}
Update 文檔
- Update 不會刪除原來文檔,而是實現真正更新
- Post 方法和 Payload 需要包含在 "doc" 中
#在原文檔上增加字段
POST songs/_update/1
{
"doc":{
"update" : "2019-05-15T14:12:12"
}
}
GET songs/_doc/1
{
"_index" : "songs",
"_type" : "_doc",
"_id" : "1",
"_version" : 3,
"_seq_no" : 2,
"_primary_term" : 1,
"found" : true,
"_source" : {
"name" : "說好不哭",
"author" : "周傑倫",
"price" : 0,
"update" : "2019-05-15T14:12:12"
}
}
Delete 文檔
#Delete by Id
#刪除文檔
DELETE users/_doc/1
Bulk 批量操作
- Bulk 支持再一次調用中,對不同索引進行操作
- 支持 Index、Create、Update、Delete 類型操作
- 單條錯誤不影響其他操作進行
- 每一條操作都會有對應的執行的結果顯示
POST _bulk
{ "index" : { "_index" : "test1", "_id" : "1" } }
{ "field1" : "value1" }
{ "delete" : { "_index" : "test1", "_id" : "2" } }
{ "create" : { "_index" : "test2", "_id" : "3" } }
{ "field3" : "value3" }
{ "update" : { "_index" : "test1","_id" : "1"} }
{ "doc" : {"field2" : "value2"} }
mget 批量讀取
顧名思義就是可以對不同索引的文檔進行批量讀取,只需要提供索引名稱和 Id 就可以在一次 API 中全部讀取,減少網絡開銷。
GET /test1/_mget
{
"docs" : [
{
"_id" : "1"
},
{
"_id" : "2"
}
]
}
msearch 批量查詢
同樣 ES 也提供了 msearch 對不同索引進行批量查詢。
# msearch 操作
POST kibana_sample_data_ecommerce/_msearch
{}
{"query" : {"match_all" : {}},"size":1}
{"index" : "kibana_sample_data_flights"}
{"query" : {"match_all" : {}},"size":2}
注:kibana_sample_data_ecommerce 可以在 kibana 的樣例數據,需要手動點擊添加。
本篇主要對文檔的 CRUD 以及批量操作 API 進行講解。在這里提一點,批量操作可以幫助我們提高對 API 調用性能,但如果一次提交過多數據,也是有可能會導致 ES 過大的壓力,反而造成性能下降。
系列文章