Elasticsearch 管理文檔

來源:互聯網
上載者:User

標籤:

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 管理文檔

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.