我正在尝试使用节点创建Azure文档数据库(cosmos DB)分区集合。
function _getOrCreateCollectionAsync(databaseUrl, collection){
var collectionUrl = `${databaseUrl}/colls/${collection.name}`,
def = Q.defer();
console.log("getting collection: " + collectionUrl);
client.readCollection(collectionUrl, (err, result) => {
if (err) {
if (err.code == 404) {
console.log("collection " + collection.name + " not found... creating...");
var colOptions = {};
colOptions.offerThroughput = collection.azureOptions.offerThroughput || 10000; //default is 10k
colOptions.partitionKey = ["/data"];
// colOptions.partitionKey = ["data"];
// colOptions.partitionKey = "/data";
// colOptions.partitionKey = "data";
var reqOptions = {
id : collection.name
//, partitionKey : ["/data"]
}
client.createCollection(databaseUrl, reqOptions, colOptions, (err, created) => {
if (err) {
console.log(err);
def.reject(err)
} else {
def.resolve(created);
}
});
} else {
console.log(err);
def.reject(err);
}
} else {
def.resolve(result);
}
});
return def.promise;
}
(请忽略代码邋,,我仍然试图让它工作)
当我运行此操作时,我收到此错误
.......... working with collection: testCollection
getting collection: dbs/testDb/colls/testCollection
collection testCollection not found... creating...
{ code: 400,
body: '{"code":"BadRequest","message":"Message: {\\"Errors\\":[\\"x-ms-documentdb-partitionkey header cannot be specified for this request\\"]}\\r\\nActivityId: (snip), Request URI: /apps/(snip)/services/(snip)/partitions/(snip)/replicas/(snip)"}',
activityId: '(snip)' }
从上面我可以看到,我有不同的选项来定义分区键,它们都返回相同的结果。
我还尝试使用此示例Create Collection in Azure DocumentDB with Different Partition Mode作为指南(在c#中)将其添加到reqOptions中,这表明他需要将分区键作为reqOptions对象的一部分。当我这样做时,我得到了这个错误。
.......... working with collection: testCollection
getting collection: dbs/testDb/colls/testCollection
collection testCollection not found... creating...
{ code: 400,
body: '{"code":"BadRequest","message":"The specified document collection is invalid.\\r\\nActivityId: (snip)"}',
activityId: '(snip)' }
此时我不知所措,我们将非常感谢任何帮助。
由于
答案 0 :(得分:1)
如Cosmos DB REST API documentation所述,必须将分区键指定为对象并放入请求正文中。
所以,请更改您的代码如下:
var colOptions = {};
colOptions.offerThroughput = collection.azureOptions.offerThroughput || 10000; //default is 10k
var reqOptions = {
id: collection.name,
partitionKey : { paths: ["/data"], kind: "Hash" }
}
client.createCollection(databaseUrl, reqOptions, colOptions, (err, created) => {
if (err) {
console.log(err);
def.reject(err)
} else {
def.resolve(created);
}
});