ES支持近實時的索引、更新、查詢、刪除文檔,近實時就意味着剛剛索引的數據須要1秒鐘後才能搜索到,這也是與傳統的SQL數據庫不一樣的地方。html
更多的ES文檔資料參考:Elasticsearch官方文檔翻譯數據庫
以前已經試過如何索引一個文檔了,這裏再複習一下:curl
curl -XPUT 'localhost:9200/customer/external/1?pretty' -d ' { "name": "John Doe" }'
上面的例子中,建立了一個索引爲customer,類型爲external,id爲1的文檔。url
當再次執行命令:spa
curl -XPUT 'localhost:9200/customer/external/1?pretty' -d ' { "name": "Jane Doe" }'
以前的第一個文檔就被覆蓋掉了。翻譯
若是指定新的文檔id,那麼舊的文檔仍然存在:code
curl -XPUT 'localhost:9200/customer/external/2?pretty' -d ' { "name": "Jane Doe" }'
索引的時候ID是可選的,若是不指定ID,ES會隨機生成一個ID,並使用這個ID索引文檔數據。htm
curl -XPOST 'localhost:9200/customer/external?pretty' -d ' { "name": "Jane Doe" }'
須要注意的是,若是不指定ID,那麼須要使用POST命令,而不是PUT。blog
除了索引和替換文檔,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中的某一個命令執行出錯,那麼會繼續執行後面的命令,最後在命令返回時,會返回每一個命令的執行結果。