英文:
How to access partition key from an existing table in cosmos db
问题
我正在尝试访问 Cosmos DB 中现有集合的分区键。
我已经阅读了官方文档和 GitHub 链接,但没有成功。请帮助我。
注意:我能够使用 Java 通过 Document Client(SQL API)成功读写数据。
英文:
I'm trying to access only partition key of an existing collection in cosmos db
I have gone through official doc and git hub links but no luck. Please help me.
Note: I'm able to successfully read and write data using java by using Document Client(SQL api)
答案1
得分: 1
请尝试以下代码:
DocumentClient dClient = new DocumentClient(endPoint, primary_key, null, null);
String collectionLink = String.format("/dbs/%s/colls/%s", databaseId, collectionId);
ResourceResponse<DocumentCollection> response = dClient.readCollection(collectionLink, new RequestOptions());
DocumentCollection documentCollection = response.getResource();
PartitionKeyDefinition partitionKeyDefinition = documentCollection.getPartitionKey();
Collection<String> paths = partitionKeyDefinition.getPaths();
if (paths.iterator().hasNext()) {
System.out.println(paths.iterator().next());
}
英文:
Please try this code:
DocumentClient dClient = new DocumentClient(endPoint,primary_key,null,null);
String collectionLink = String.format("/dbs/%s/colls/%s", databaseId, collectionId);
ResourceResponse<DocumentCollection> response = dClient.readCollection(collectionLink,new RequestOptions());
DocumentCollection documentCollection = response.getResource();
PartitionKeyDefinition partitionKeyDefinition = documentCollection.getPartitionKey();
Collection<String> paths = partitionKeyDefinition.getPaths();
if(paths.iterator().hasNext()){
System.out.println(paths.iterator().next());
}
答案2
得分: 0
我发现这段代码可行:
_container 是用于 Cosmos 数据库的容器。
var settings = await _container!.ReadContainerAsync(cancellationToken: cancellationToken);
var partitionKeyPath = settings.Resource.PartitionKeyPath[1..];
var partitionProperty = typeof(T).GetProperty(partitionKeyPath);
var partitionKey = partitionProperty!.GetValue(message)!.ToString();
英文:
I found this works:
_container is the db container for cosmos.
var settings = await _container!.ReadContainerAsync(cancellationToken: cancellationToken);
var partitionKeyPath = settings.Resource.PartitionKeyPath[1..];
var partitionProperty = typeof(T).GetProperty(partitionKeyPath);
var partitionKey = partitionProperty!.GetValue(message)!.ToString();
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论