从MongoDB Java驱动程序版本2.10.1设置分片键的语法是什么?
或者换句话说,我如何使用Java驱动程序执行此操作?
sh.shardCollection("test.a", {"_id": "hashed"}})
答案 0 :(得分:6)
简短回答:您应该发出shardCollection
命令。
答案很长:
MongoDB shell中的sh.shardCollection
只是在admin
db上调用命令的辅助方法。
如果在MongoDB shell中输入sh.shardCollection
,您将看到此函数实际执行的操作:
> sh.shardCollection
function ( fullName , key , unique ) {
sh._checkFullName( fullName )
assert( key , "need a key" )
assert( typeof( key ) == "object" , "key needs to be an object" )
var cmd = { shardCollection : fullName , key : key }
if ( unique )
cmd.unique = true;
return sh._adminCommand( cmd );
}
然后,您可以在MongoDB shell中调用sh._adminCommand
:
> sh._adminCommand
function ( cmd , skipCheck ) {
if ( ! skipCheck ) sh._checkMongos();
return db.getSisterDB( "admin" ).runCommand( cmd );
}
当你把所有这些放在一起时,所有sh.shardCollection
命令都在检查参数并调用这个命令:
db.getSisterDB( "admin" ).runCommand({
shardCollection : "test.a" ,
key : {"_id": "hashed"}
});
Java语法:
DBObject cmd = new BasicDBObject("shardCollection", "test.a").
append("key",new BasicDBObject("_id", "hashed"));
CommandResult r = db.getSisterDB("admin").command(cmd);
答案 1 :(得分:0)
通过Java api设置分片:
CommandResult result=null;
// The only way to shard this is via executing a command. If this is not
// done the collection will becreated but it will not be
// sharded. The first arg is the key and the second one is the logic to be used
final BasicDBObject shardKey = new BasicDBObject("_id", "hashed");
final BasicDBObject cmd = new BasicDBObject("shardCollection", "test."+collectionName);
cmd.put("key", shardKey);
// RUnning the command to create the sharded collection
result = mongoClient.getDB("admin").command(cmd);
System.out.println("Collection created successfully");
// loading the collection and then will be insterting the data
final DBCollection shardCollection = mongoClient.getDB("test").getCollection(collectionName);
// Here i am using a arraylist values which has all the data
shardCollection.insert(values);
System.out.println("Collection added");
答案 2 :(得分:-1)
没有API。您必须发出命令来设置该分片键。