Search code examples
javaazureazure-cosmosdbazure-cosmosdb-sqlapi

How to access partition key from an existing table in cosmos db


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)


Solution

  • 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());
    }