首页 文章

Azure DocumentDB SDK Java:使用分区键插入单个文档时出现问题

提问于
浏览
0

我的代码中有一个方法,负责将单个文档插入到cosmosDB中 . 当我以前在RequestOptions中未指定partitionId时插入文档时它曾经工作正常:

public Document createOne(JSONObject aJSONObject)  throws DocumentClientException {
    Document aDocument = new Document(aJSONObject.toString());            
    return documentClient.createDocument(getCollectionLink(), aDocument, null, false).getResource();
}

但是如果我改变我的代码来传递_1786408中的partitionId,就像这样:

public Document createOne(JSONObject aJSONObject, String aPartitionKeyStr)  throws DocumentClientException {
    Document aDocument = new Document(aJSONObject.toString());

    PartitionKey aPartitionKey = new PartitionKey(aPartitionKeyStr);
    RequestOptions requestOptions = new RequestOptions();
    requestOptions.setPartitionKey(aPartitionKey);

    return documentClient.createDocument(getCollectionLink(), aDocument, requestOptions, false).getResource();
}

我收到上述错误: PartitionKey extracted from document doesn't match the one specified in the header . 我'm pretty sure i' m正确传递分区键值,因为我有相同的 createMany 方法,它使用存储过程进行批量插入并在requestOptions中传递partitionKey,它在Internet上查找并发现类似的问题似乎与我的问题有关像thisthis,但他们专注于正确传递partitionKey . 我'm sure i' m正确传递了partitionKey .

在我们的集合中, /clientId 键用作分区键,在插入函数的第一行设置断点给出output,aPartitionKey打印如下: ["shiv-postman-client"]

我有一个疑问,在插入单个文档时传递partitionKey会对性能有任何改进吗?我在azure的sdk文档中也看到here(显示分区集合用法的示例),他们在插入时没有使用分区键,只在查询期间 .

1 回答

  • 1

    要插入单个文档,您不需要在请求选项中指定 Partition Key 值 .

    如果查看Creating a Document的REST API文档,您会注意到那里没有 x-ms-documentdb-partitionkey 标头 . 这就是为什么在请求选项中没有指定分区键(它作为请求头发送)时,代码可以工作的原因 .

    如果您尝试更新文档,则需要在请求选项中指定 PartitionKey 值 . 请参阅Replace Document REST API .

相关问题