mongodb分片介紹—— 基於范圍(數值型)的分片 或者 基於哈希的分片


數據分區

MongoDB中數據的分片是以集合為基本單位的,集合中的數據通過 片鍵 被分成多部分.

片鍵

  • 對集合進行分片時,你需要選擇一個 片鍵 , shard key 是每條記錄都必須包含的,且建立了索引的單個字段或復合字段,MongoDB按照片鍵將數據划分到不同的 數據塊 中,並將 數據塊 均衡地分布到所有分片中.為了按照片鍵划分數據塊,MongoDB使用 基於范圍的分片方式 或者 基於哈希的分片方式。

以范圍為基礎的分片

對於 基於范圍的分片 ,MongoDB按照片鍵的范圍把數據分成不同部分.假設有一個數字的片鍵:想象一個從負無窮到正無窮的直線,每一個片鍵的值都在直線上畫了一個點.MongoDB把這條直線划分為更短的不重疊的片段,並稱之為 數據塊 ,每個數據塊包含了片鍵在一定范圍內的數據.

在使用片鍵做范圍划分的系統中,擁有”相近”片鍵的文檔很可能存儲在同一個數據塊中,因此也會存儲在同一個分片中.

Diagram of the shard key value space segmented into smaller ranges or chunks.

基於哈希的分片

對於 基於哈希的分片 ,MongoDB計算一個字段的哈希值,並用這個哈希值來創建數據塊.

在使用基於哈希分片的系統中,擁有”相近”片鍵的文檔 很可能不會 存儲在同一個數據塊中,因此數據的分離性更好一些.

Diagram of the hashed based segmentation.

基於范圍的分片方式與基於哈希的分片方式性能對比

基於范圍的分片方式提供了更高效的范圍查詢,給定一個片鍵的范圍,分發路由可以很簡單地確定哪個數據塊存儲了請求需要的數據,並將請求轉發到相應的分片中.

不過,基於范圍的分片會導致數據在不同分片上的不均衡,有時候,帶來的消極作用會大於查詢性能的積極作用.比如,如果片鍵所在的字段是線性增長的,一定時間內的所有請求都會落到某個固定的數據塊中,最終導致分布在同一個分片中.在這種情況下,一小部分分片承載了集群大部分的數據,系統並不能很好地進行擴展.

與此相比,基於哈希的分片方式以范圍查詢性能的損失為代價,保證了集群中數據的均衡.哈希值的隨機性使數據隨機分布在每個數據塊中,因此也隨機分布在不同分片中.但是也正由於隨機性,一個范圍查詢很難確定應該請求哪些分片,通常為了返回需要的結果,需要請求所有分片.

均衡

The balancer is a background process that manages chunk migrations. The balancer can run from any of themongos instances in a cluster.

當集群中數據的不均衡發生時,均衡器會將數據塊從數據塊數目最多的分片遷移到數據塊最少的分片上,舉例來講:如果集合 users 在 分片1 上有100個數據塊,在 分片2 上有50個數據塊,均衡器會將數據塊從 分片1一直向 分片2 遷移,一直到數據均衡為止.

The shards manage chunk migrations as a background operation between an origin shard and a destination shard. During a chunk migration, the destination shard is sent all the current documents in the chunk from theorigin shard. Next, the destination shard captures and applies all changes made to the data during the migration process. Finally, the metadata regarding the location of the chunk on config server is updated.

If there’s an error during the migration, the balancer aborts the process leaving the chunk unchanged on the origin shard. MongoDB removes the chunk’s data from the origin shard after the migration completes successfully.

Diagram of a collection distributed across three shards. For this collection, the difference in the number of chunks between the shards reaches the *migration thresholds* (in this case, 2) and triggers migration.


免責聲明!

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



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