Elasticsearch 管理文檔


ES支持近實時的索引、更新、查詢、刪除文檔,近實時就意味着剛剛索引的數據需要1秒鍾后才能搜索到,這也是與傳統的SQL數據庫不同的地方。

更多的ES文檔資料參考:Elasticsearch官方文檔翻譯

索引/替換文檔

之前已經試過如何索引一個文檔了,這里再復習一下:

curl -XPUT 'localhost:9200/customer/external/1?pretty' -d '
{
  "name": "John Doe"
}'

上面的例子中,創建了一個索引為customer,類型為external,id為1的文檔。

當再次執行命令:

curl -XPUT 'localhost:9200/customer/external/1?pretty' -d '
{
  "name": "Jane Doe"
}'

之前的第一個文檔就被覆蓋掉了。

 

如果指定新的文檔id,那么舊的文檔仍然存在:

curl -XPUT 'localhost:9200/customer/external/2?pretty' -d '
{
  "name": "Jane Doe"
}'

 

索引的時候ID是可選的,如果不指定ID,ES會隨機生成一個ID,並使用這個ID索引文檔數據。

curl -XPOST 'localhost:9200/customer/external?pretty' -d '
{
  "name": "Jane Doe"
}'

需要注意的是,如果不指定ID,那么需要使用POST命令,而不是PUT。

更新文檔

除了索引和替換文檔,ES還支持更新文檔。更新文檔其實是先刪除舊的文檔,再索引新的文檔。

如果想要更新文檔內容,可以按照下面的方式進行:

curl -XPOST 'localhost:9200/customer/external/1/_update?pretty' -d '
{
  "doc": { "name": "Jane Doe" }
}'

由於是先刪除再索引,因此可以額外增加新的字段:

curl -XPOST 'localhost:9200/customer/external/1/_update?pretty' -d '
{
  "doc": { "name": "Jane Doe", "age": 20 }
}'

當然也支持使用腳本進行更新:

curl -XPOS
T 'localhost:9200/customer/external/1/_update?pretty' -d ' { "script" : "ctx._source.age += 5" }'

其中ctx._source代表了當前的文檔,上面的意思 是 在當前文檔的基礎上age加5.

刪除文檔

刪除文檔就很簡單了,只需要指定文檔的索引、類型、ID就行了:

curl -XDELETE 'localhost:9200/customer/external/2?pretty'

 

批量操作

除了索引、替換、更新和刪除,ES為了減少來回的響應信息,可以一次性執行多個命令,最后統一返回執行結果。

例如:

curl -XPOST 'localhost:9200/customer/external/_bulk?pretty' -d '
{"index":{"_id":"1"}}
{"name": "John Doe" }
{"index":{"_id":"2"}}
{"name": "Jane Doe" }
'

上面的命令可以同時插入兩條數據。

_bulk命令不僅僅支持單個命令執行多條,還只是多種不同的命令執行多條。

curl -XPOST 'localhost:9200/customer/external/_bulk?pretty' -d '
{"update":{"_id":"1"}}
{"doc": { "name": "John Doe becomes Jane Doe" } }
{"delete":{"_id":"2"}}
'

上面的命令中,先更新id為1的文檔,再刪除id為2的文檔。

 

如果bulk中的某一個命令執行出錯,那么會繼續執行后面的命令,最后在命令返回時,會返回每個命令的執行結果。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM