【4. 对数据库启用分片】
4.1 当前可连接到 mongos 查看数据库或者集合的分片情况(没有分片):
mongos> db.stats() mongos> db.tab.stats()4.2 对数据库激活分片功能:
[root@mongodb11 ~]# mongo 192.168.1.11:27016
mongos> sh.enableSharding("test")
#或者
[root@mongodb11 ~]# mongo 192.168.1.11:27016
mongos> use admin
mongos> db.runCommand( { enableSharding: "test"} )
4.3 此时查看数据库分区情况,partitioned 变为 “true”。
configsvr> use config
switched to db config
configsvr> db.databases.find()
{ "_id" : "admin", "partitioned" : false, "primary" : "config" }
{ "_id" : "mydb", "partitioned" : true, "primary" : "shard0000" }
{ "_id" : "test", "partitioned" : true, "primary" : "shard0000" } 启用数据库分片并没有将数据进行分开,还需要对 collection 进行分片。
【5. 对集合启用分片】
启用前,有几个问题需要考虑的:
1. 选择哪个键列作为 shard key 。(更多参考: Considerations for Selecting Shard Keys)
2. 如果集合中已经存在数据,在选定作为shard key 的键列必须创建索引;如果集合为空,mongodb 将在激活集合分片(sh.shardCollection)时创建索引。
3. 集合分片函数 sh.shardCollection ,
sh.shardCollection("
mongos> sh.shardCollection("test.tab", { "_id": "hashed" })
测试:
for (var i=1; i<100000; i++) {
db.kk.insert({"id": i, "myName" : "kk"+i, "myDate" : new Date()});
}
mongos> show collections
mongos> db.kk.find()
mongos> db.kk.createIndex({ "id": "hashed" })
mongos> db.kk.getIndexes()
mongos> sh.shardCollection("test.kk", { "id": "hashed" })
mongos> db.stats()
mongos> db.kk.stats()
由于数据分区需要时间,过会再查看数据分布情况:
总行数:99999
mongos> db.kk.count() 99999
mongos> db.printShardingStatus();
--- Sharding Status ---
sharding version: {
"_id" : 1,
"minCompatibleVersion" : 5,
"currentVersion" : 6,
"clusterId" : ObjectId("556023c02c2ebfdfbc8d39eb")
}
shards:
{ "_id" : "shard0000", "host" : "mongodb11.kk.net:27017" }
{ "_id" : "shard0001", "host" : "mongodb12.kk.net:27018" }
{ "_id" : "shard0002", "host" : "mongodb13.kk.net:27019" }
balancer:
Currently enabled: yes
Currently running: no
Failed balancer rounds in last 5 attempts: 0
Migration Results for the last 24 hours:
1334 : Success
2 : Failed with error 'could not acquire collection lock for test.kk to migrate chunk [{ : MinKey },{ : MaxKey }) :: caused by :: Lock for migrating chunk [{ : MinKey }, { : MaxKey }) in test.kk is taken.', from shard0000 to shard0001
databases:
{ "_id" : "admin", "partitioned" : false, "primary" : "config" }
{ "_id" : "mydb", "partitioned" : true, "primary" : "shard0000" }
{ "_id" : "test", "partitioned" : true, "primary" : "shard0000" }
test.kk
shard key: { "id" : "hashed" }
chunks:
shard0000 667
shard0001 667
shard0002 667
too many chunks to print, use verbose if you want to force print
{ "_id" : "events", "partitioned" : false, "primary" : "shard0002" }
mongos>
看这里 chunks :
shard0000 667
sha