標籤:
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中的某一個命令執行出錯,那麼會繼續執行後面的命令,最後在命令返回時,會返回每個命令的執行結果。
Elasticsearch 管理文檔