Elasticsearch 5.0-基本操作
標籤 : Elasticsearch
本文是 Elasticsearch 5.0 系列博文的基本操作篇,主要介紹 Elasticsearch 的 CRUD 操作
寫在前面
- 本文以 Elasticsearch 5.0.1 版本爲例進行講解,不定期更新
- 該系列主要參考的 Elasticsearch Reference: 5.0,儘量避免照搬翻譯,只摘錄精要部分輔以簡單說明
- 寫這個系列博客的初衷是強迫自己梳理,同時方便一些較忙/沒空耐心看英文文檔的朋友快速上手,建議讀者有空多讀官方文檔,畢竟別人寫的都是二手資料
- 如需查看 ES 系列更多博文,請關注我的個人網站@brianway 或者 @CSDN
基礎指令
下面是在 Console
中輸入的一些命令,可以依次運行看看結果。
# Cluster Health
GET _cat/health?v
# list of nodes
GET /_cat/nodes?v
#List All Indices
GET /_cat/indices?v
# Create an Index
PUT /customer?pretty
GET /_cat/indices?v
# Index and Query a Document
PUT /customer/external/1?pretty
{
"name": "John Doe"
}
GET /customer/external/1?pretty
DELETE /customer/external/1
# Delete an Index
DELETE /customer?pretty
可以看出Elasticsearch 的 REST API基本格式:
<REST Verb> /<Index>/<Type>/<ID>
索引/替換文檔
# Indexing/Replacing Documents
PUT /customer/external/1?pretty
{
"name": "John Doe"
}
# using the POST verb instead of PUT since we didn’t specify an ID
POST /customer/external?pretty
{
"name": "Jane Doe"
}
- 使用
PUT
方法需要明確指定 ID,兩次 PUT 的 id 相同則是替換之前的文檔,第二次 id 不同則是創建新的文檔 - 沒明確指定 ID 則使用
POST
方法
更新文檔
# Updating Documents
POST /customer/external/1/_update?pretty
{
"doc": { "name": "Jane Doe" }
}
POST /customer/external/1/_update?pretty
{
"doc": { "name": "Jane Doe", "age": 20 }
}
# uses a script to increment the age by 5
POST /customer/external/1/_update?pretty
{
"script" : "ctx._source.age += 5"
}
更新文檔其實就是先刪除再建一個新的文檔
Whenever we do an update, Elasticsearch deletes the old document and then indexes a new document with the update applied to it in one shot
刪除文檔
# Deleting Documents
DELETE /customer/external/2?pretty
直接刪除整個 index 要比刪除 index 裏的所有文檔要更有效率
It is worth noting that it is much more efficient to delete a whole index instead of deleting all documents with the Delete By Query API.
批處理
# Batch Processing
POST /customer/external/_bulk?pretty
{"index":{"_id":"1"}}
{"name": "John Doe" }
{"index":{"_id":"2"}}
{"name": "Jane Doe" }
POST /customer/external/_bulk?pretty
{"update":{"_id":"1"}}
{"doc": { "name": "John Doe becomes Jane Doe" } }
{"delete":{"_id":"2"}}
- 刪除操作後面沒有相應的文檔數據,只提供要刪除的 ID 即可
- 批處理對每個操作(action)按順序依次執行(sequentially and in order),如果單個操作出錯,也會繼續執行剩下的操作
- 批處理放回結果時,按照請求順序爲每個操作提供一個狀態以便用戶檢查