Elasticsearch 存儲一條數(shù)據(jù), put 過程是什么樣子的?
前言
在前面已經(jīng)介紹了 ES 中常用的一些名詞,知道了數(shù)據(jù)是存儲在 shard 中的,而 index 會映射一個或者多個 shard 。那這時候我要存儲一條數(shù)據(jù)到某個索引下,這條數(shù)據(jù)是在哪個 index 下的呢? "
1.ES演示
一切按照官方教程使用 三條命令,在本機啟動三個節(jié)點組裝成偽集群。
- ~ % > ./elasticsearch
- ~ % > ./elasticsearch -Epath.data=data2 -Epath.logs=log2
- ~ % > ./elasticsearch -Epath.data=data3 -Epath.logs=log3
創(chuàng)建一個索引
- curl -X PUT "localhost:9200/my-index-000001?pretty" -H 'Content-Type: application/json' -d'
- {
- "settings": {
- "index": {
- "number_of_shards": 3,
- "number_of_replicas": 2
- }
- }
- }
- '
當前版本 7.9
ES 默認 number_of_shards 為 1
默認 number_of_replicas 為 1,即一個分片只有一個副本
下面命令可以查看索引信息:
- curl -X GET "localhost:9200/_cat/indices/my-index-000001?v&s=index&pretty"
存放數(shù)據(jù)
- curl -X PUT "localhost:9200/my-index-000001/_doc/0825?pretty" -H 'Content-Type: application/json' -d'
- {
- "name": "liuzhihang"
- }
- '
查詢數(shù)據(jù)
- curl -X GET "localhost:9200/my-index-000001/_doc/0825?pretty"
2.一條數(shù)據(jù)該存放在哪個 shard ?
通過命令可以看出:在存放數(shù)據(jù)時并沒有指定到哪個 shard,那數(shù)據(jù)是存在哪里的呢?
當一條數(shù)據(jù)進來,會默認會根據(jù) id 做路由:
- shard = hash(routing) % number_of_primary_shards
從而確定存放在哪個 shard。routing 默認是 _id, 也可以設(shè)置其他。
這個 id 可以自己指定也可以系統(tǒng)給生成, 如果不指定則會系統(tǒng)自動生成。
3.put 一條數(shù)據(jù)的過程是什么樣的?
寫入過程主要分為三個階段
1.協(xié)調(diào)階段:Client 客戶端選擇一個 node 發(fā)送 put 請求,此時當前節(jié)點就是協(xié)調(diào)節(jié)點(coordinating node)。協(xié)調(diào)節(jié)點根據(jù) document 的 id 進行路由,將請求轉(zhuǎn)發(fā)給對應(yīng)的 node。這個 node 上的是 primary shard 。
2.主要階段:對應(yīng)的 primary shard 處理請求,寫入數(shù)據(jù) ,然后將數(shù)據(jù)同步到 replica shard。
- primary shard 會驗證傳入的數(shù)據(jù)結(jié)構(gòu)
- 本地執(zhí)行相關(guān)操作
- 將操作轉(zhuǎn)發(fā)給 replica shard
3.當數(shù)據(jù)寫入 primary shard 和 replica shard 成功后,路由節(jié)點返回響應(yīng)給 Client。
4.副本階段:每個 replica shard 在轉(zhuǎn)發(fā)后,會進行本地操作。
在寫操作時,默認情況下,只需要 primary shard 處于活躍狀態(tài)即可進行操作。
在索引設(shè)置時可以設(shè)置這個屬性
index.write.wait_for_active_shards
默認是 1,即 primary shard 寫入成功即可返回。
如果設(shè)置為 all 則相當于 number_of_replicas+1 就是 primary shard 數(shù)量 + replica shard 數(shù)量。就是需要等待 primary shard 和 replica shard 都寫入成功才算成功。
可以通過索引設(shè)置動態(tài)覆蓋此默認設(shè)置。
4.總結(jié)
如何看一條數(shù)據(jù)在哪個 shard 上呢?
curl -X GET "localhost:9200/my-index-000001/_search_shards?routing=0825&pretty"
通過上面命令可以查到數(shù)據(jù) 0825 的所在 shard。
相關(guān)資料
[1] ES 創(chuàng)建索引:
https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-create-index.html
[2] ES 查詢數(shù)據(jù):
https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-get.html
[2] ES 檢索 shard:
https://www.elastic.co/guide/en/elasticsearch/reference/current/search-shards.html
本文轉(zhuǎn)載自微信公眾號「劉志航」,可以通過以下二維碼關(guān)注。轉(zhuǎn)載本文請聯(lián)系劉志航公眾號。