一、使用Ranged Sharding对集合进行分片

mongo连接到的shell中mongos,使用该sh.shardCollection()方法对集合进行分片。



注意:

  • 必须已为集合所在的数据库启用了分片。
  • 如果集合已包含数据,则必须在使用之前使用该方法在分片键上创建索引 。db.collection.createIndex()shardCollection()
  • 如果集合为空,MongoDB将创建索引作为其中的一部分 sh.shardCollection()

二、使用hash值对集合进行分片

MongoDB计算每个字段的hash值,然后用这些hash值建立chunks。

注意:

哈希分片牺牲了范围查询的性能,让数据相对均匀的分配到各个分片上

三、范围分片实践


(1) 集群中创建数据库eshop和集合users,并増加一条记录。


use eshop
db.users.insert({userid:1,username:"localD",city:"guangzhou"})



 



(2) 观察集群的状态信息,连接mongos端口使用该sh.enableSharding()方法在目标数据库上启用分片。在数据库上启用分片可以在数据库中分片集合。



sh.status()//观察集群的状态信息
sh.enableSharding("eshop")//让数据库shop支持分片


 

PerconaServerMongoDB 集群切片_ci

 

(3) 创建基于片键city的索引,并且设置启用集合分片



db.users.ensureIndex({city:1})//创建基于片键city的索引
sh.shardCollection("eshop.users",{city:1})//启用集合分片


 

PerconaServerMongoDB 集群切片_数据_02

 


 (4) 继续观察集群状态


PerconaServerMongoDB 集群切片_数据_03

PerconaServerMongoDB 集群切片_shell_04

 

(5) 继续插入大量数据使集合进行分片


for(var i=1;i<=10000;i++){db.users.insert({userid:i,username:'auser'+i,city:'shenzhen'})}
for(var i=1;i<=10000;i++){db.users.insert({userid:i,username:'buser'+i,city:'beijin'})}
for(var i=1;i<=10000;i++){db.users.insert({userid:i,username:'cuser'+i,city:'hunan'})}

  

PerconaServerMongoDB 集群切片_数据_05

 

 

(6) 继续观察集群状态

 

PerconaServerMongoDB 集群切片_shell_06

PerconaServerMongoDB 集群切片_数据库_07

 

PerconaServerMongoDB 集群切片_ci_08

 

 (7) 分别查看分片1、分片2和分片3的存储数据数量

在分片1节点上的数据:

 

PerconaServerMongoDB 集群切片_shell_09

 

在分片2节点上的数据:

PerconaServerMongoDB 集群切片_数据库_10

 

在分片3节点上的数据:

 

PerconaServerMongoDB 集群切片_ci_11

 


四、哈希分片实践

(1) 集群中创建数据库Hash和使用该sh.enableSharding()方法启用分片。


sh.enableSharding("Hash")


 

(2)并且设置启用哈希分片


sh.shardCollection("Hash.Hash",{"Uid":"hashed"})


  

(3)插入大量数据使集合进行分片


use Hash
for(i=0;i<10000;i++){ db.Hash.insert({"Uid":i,"Name":"da","Age":21})}


  

(4) 继续观察集群状态  


sh.status()

  

PerconaServerMongoDB 集群切片_shell_12

分别在分片上查看具体数据

PerconaServerMongoDB 集群切片_数据库_13

PerconaServerMongoDB 集群切片_ci_14

PerconaServerMongoDB 集群切片_ci_15

 

 

PerconaServerMongoDB 集群切片_数据库_16

 

 

三、分片集群常用的管理命令
1、添加分片


sh.addShard( "<ip>:<端口>" )


2、删除分片


#需要运行两次,如果删除的是大本营,必须先要把数据库移到别的分片上或者删除该数据库
db.runCommand({"removeshard":"<ip>:<端口>"})


3、修改chunk的大小


db.settings.save( { _id:"chunksize", value: 1 } )db.settings.find()


4、刷新config服务器路由


use admindb.runCommand("flushRouterConfig");


5、对数据库/集合进行分片


sh.enableSharding("Hash") 或者  db.runCommand({"enablesharding":"eshop"})
sh.shardCollection("Hash.Hash",{"Uid":1}) 或者 db.runCommand({"shardcollection":"eshop.users","key":{"city":1}})
sh.shardCollection("HashTest.HashTest",{"Uid":"hashed"})   //hash分片


6、查看分片集群的状态


sh.status()


7、查看config库信息


use config  
     db.shards.find()//查看分片信息 
     db.databases.find()//查看分片数据库信息 

     db.chunks.find()//查看块信息

 

PerconaServerMongoDB 集群切片_ci_17