如何从 Cosmos DB 中的现有表中访问分区键。

huangapple go评论67阅读模式
英文:

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(&quot;/dbs/%s/colls/%s&quot;, databaseId, collectionId);
ResourceResponse&lt;DocumentCollection&gt; response = dClient.readCollection(collectionLink,new RequestOptions());
DocumentCollection documentCollection = response.getResource();
PartitionKeyDefinition partitionKeyDefinition = documentCollection.getPartitionKey();
Collection&lt;String&gt; 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();

huangapple
  • 本文由 发表于 2020年9月8日 17:37:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/63791156.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定