MCPcopy
hub / github.com/alibaba/MongoShake / preShardingForHashed

Function preShardingForHashed

tools/pre-split/pre_split.go:582–622  ·  view source on GitHub ↗

preShardingForHashed does the pre-sharding work for hashed sharding

(srcC, dstC *mongo.Client, dbName, collName string, shardKey bson.D,
	unique bool, uuid *primitive.Binary, chunkNum int64)

Source from the content-addressed store, hash-verified

580
581// preShardingForHashed does the pre-sharding work for hashed sharding
582func preShardingForHashed(srcC, dstC *mongo.Client, dbName, collName string, shardKey bson.D,
583 unique bool, uuid *primitive.Binary, chunkNum int64) error {
584 // simple use 'shardCollection' with 'numInitialChunks' option,
585 // but only when the hashed index key is the prefix of shard key
586 if shardKey[0].Value == "hashed" {
587 // run 'enableSharding', it's ok to run multi times
588 if SrcV.GTE(Version600) {
589 cmd := bson.D{{Key: "enableSharing", Value: dbName}}
590 if *dryRun {
591 log.Infof("[DRY_RUN] db.adminCommand( %v )", cmd)
592 } else {
593 res := dstC.Database(DbAdmin).RunCommand(context.Background(), cmd)
594 if res.Err() != nil {
595 return fmt.Errorf("error enabling sharding for %s: %v", dbName, res.Err())
596 }
597 }
598 }
599
600 // run 'shardCollection'
601 // todo: support other options like 'collation'/'timeseries'
602 cmd := bson.D{
603 {Key: "shardCollection", Value: fmt.Sprintf("%s.%s", dbName, collName)},
604 {Key: "key", Value: shardKey},
605 {Key: "unique", Value: unique},
606 {Key: "numInitialChunks", Value: chunkNum}, // 或者根据你的需求指定一个合适的值
607 }
608 if *dryRun {
609 log.Infof("[DRY_RUN] db.adminCommand( %v )", cmd)
610 } else {
611 res := dstC.Database(DbAdmin).RunCommand(context.Background(), cmd)
612 if res.Err() != nil {
613 return fmt.Errorf("error pre-splitting hashed collection %s.%s: %v", dbName, collName, res.Err())
614 }
615 }
616 } else {
617 // use preSharingForRange instead
618 return preSharingForRange(srcC, dstC, dbName, collName, shardKey, unique, uuid, chunkNum)
619 }
620
621 return nil
622}
623
624// countChunks count the number of chunks for specified sharded collection, support all db versions
625func countChunks(c *mongo.Client, dbName, collName string, uuid *primitive.Binary, dbVersion Version) (int64, error) {

Callers 1

handleNamespaceFunction · 0.85

Calls 4

GTEMethod · 0.80
InfofMethod · 0.80
ErrorfMethod · 0.80
preSharingForRangeFunction · 0.70

Tested by

no test coverage detected