默认范围分片密钥mongodb

默认范围分片密钥mongodb,mongodb,sharding,Mongodb,Sharding,我有一个mongodb碎片,有2个碎片(比如a和B),每个碎片有17GB的可用空间。我将包含对象id的_id设置为shard key 下面是用于设置数据库和集合的命令 sh.enableSharding("testShard"); sh.shardCollection("testShard.shardedCollection", {_id:1}); 然后我尝试向mongos服务器发出4000000个insert查询。我执行下面的脚本4次 for(var i=0; i<1000000; i

我有一个mongodb碎片,有2个碎片(比如a和B),每个碎片有17GB的可用空间。我将包含对象id的_id设置为shard key

下面是用于设置数据库和集合的命令

sh.enableSharding("testShard");
sh.shardCollection("testShard.shardedCollection", {_id:1});
然后我尝试向mongos服务器发出4000000个insert查询。我执行下面的脚本4次

for(var i=0; i<1000000; i++){
  db.shardedCollection.insert({x:i});
}

是的,你是对的,它应该是一块碎片。但是,在单个碎片上进行插入时,均衡器也会平衡碎片,并将块移动到其他碎片上

话虽如此,您应该做的是从mongos调用下面的命令来停止/禁用平衡器

完成后,开始插入并查看所有插入的目的地

对于_id字段切分,您也可以查看以下内容:


正如@LalitAgarwal已经指出的,objectid在默认情况下会生成一个坏的切分键。但是,如果您并不真正关心数据位于哪个碎片上,只想让写操作和数据块均匀分布在碎片之间,那么这很容易获得:

db.shardedCollection.ensureIndex({_id:"hashed"});
sh.enableSharding("testShard");
sh.shardCollection("testShard.shardedCollection", {_id:"hashed"});
但是,这也有一些(通常可以忽略不计)缺点:

  • 您有一个额外的索引,仅用于分片,没有其他用例
  • 此索引将消耗一些RAM,这是高负载生产节点上的宝贵资源
  • 在插入期间,此人工索引将需要写入操作
  • 更好的方法是找到一个非人工的切分键。详情请阅读。简言之:

  • 查找一个字段或字段组合,该字段或字段组合可以明确标识每个文档(组合中)彼此之间的差异。理想情况下,这些字段无论如何都应该是您查询的字段
  • 使用此字段或字段组合作为您的_id。由于_id字段上无论如何都需要索引,并且您需要查询这些字段,因此您消除了不需要的索引
  • 使用选定的_id字段作为切分键

  • 当均衡器被禁用时,如果第一个碎片已满,它会继续将文档写入下一个碎片吗?我认为不会。对于mongos写入任何特定碎片,该特定块范围需要存在于该碎片中。一旦禁用了平衡器,就不会有任何块指向下一个碎片。要使之成为可能,您必须手动拆分块并将其移动到另一个碎片,然后mongos将开始将数据放入另一个碎片。我将按objectId顺序阅读文档。因此,我认为牺牲在1个分片上写入是一个好主意,但当我想按顺序读取时,它也将在1个分片上本地化。不,不会,因为平衡器迟早会启动。;)
    sh.disableBalancing(namespace)
    //namespace     string  The namespace of the collection.
    
    Be aware that ObjectId() values, which are the default value of the _id field, 
    increment as a timestamp. As a result, when used as a shard key, all new documents
    inserted into the collection will initially belong to the same chunk on a single 
    shard. Although the system will eventually divide this chunk and migrate its contents 
    to distribute data more evenly, at any moment the cluster can only direct insert 
    operations at a single shard. This can limit the throughput of inserts. If most of 
    your write operations are updates, this limitation should not impact your performance. 
    However, if you have a high insert volume, this may be a limitation.
    
    db.shardedCollection.ensureIndex({_id:"hashed"});
    sh.enableSharding("testShard");
    sh.shardCollection("testShard.shardedCollection", {_id:"hashed"});