This project provides a client tools or utilities in Java that makes it easy to interact with Azure CosmosDB. For documentation please see the Microsoft Azure Java Developer Center and the JavaDocs.
Please try out our new Java V4 SDK which has support for both synchronous and asynchronous APIs - V4 SDK
The implementation in this project is intended for reference purpose only.
To get the binaries of the latest official Microsoft Azure DocumentDB Java SDK as distributed by Microsoft, ready for use within your project, you can use Maven.
<dependency>
<groupId>com.microsoft.azure</groupId>
<artifactId>azure-documentdb</artifactId>
<version>LATEST</version>
</dependency>
Version 2.4.4 have an important fix for the scenario where the SDK doesn't entertain partition split hint from server and results in incorrect client side routing caches refresh.
- Java Development Kit 7
- (Optional) Maven
Dependencies will be added automatically if Maven is used. Otherwise, please download the dependencies from the pom.xml file and add them to your build path.
We have samples in form of small executable unit tests in documentdb-examples sub project.
- Clone the Repo
git clone https://github.com/Azure/azure-documentdb-java.git
cd azure-documentdb-javaYou can run the samples either using Eclipse or from Command Line using Maven:
- Load the main parent project pom file in Eclipse (That should automatically load documentdb-examples).
- For running the samples you need a proper Azure Cosmos DB Endpoint. The endpoints are picked up from src/test/java/com/microsoft/azure/documentdb/examples/AccountCredentials.java.
- You can pass your endpoint credentials as VM Arguments in Eclipse JUnit Run Config:
-DACCOUNT_HOST="https://REPLACE_ME.documents.azure.com:443/" -DACCOUNT_KEY="REPLACE_ME"- or you can simply put your endpoint credentials in AccountCredentials.java
- Now you can run the samples as JUnit tests in Eclipse.
The other way for running samples is to use maven:
- Run Maven and pass your Azure Cosmos DB Endpoint credentials:
mvn test -DACCOUNT_HOST="https://REPLACE_ME_WITH_YOURS.documents.azure.com:443/" -DACCOUNT_KEY="REPLACE_ME_WITH_YOURS"To use this SDK to call Azure DocumentDB, you need to first create an account.
You can follow this tutorial to help you get started.
importjava.io.IOException;
importjava.util.List;
importcom.google.gson.Gson;
importcom.microsoft.azure.documentdb.ConnectionPolicy;
importcom.microsoft.azure.documentdb.ConsistencyLevel;
importcom.microsoft.azure.documentdb.Database;
importcom.microsoft.azure.documentdb.Document;
importcom.microsoft.azure.documentdb.DocumentClient;
importcom.microsoft.azure.documentdb.DocumentClientException;
importcom.microsoft.azure.documentdb.DocumentCollection;
importcom.microsoft.azure.documentdb.RequestOptions;
publicclassHelloWorld {
// Replace with your DocumentDB end point and master key.privatestaticfinalStringEND_POINT = "[YOUR_ENDPOINT_HERE]";
privatestaticfinalStringMASTER_KEY = "[YOUR_KEY_HERE]";
// Define an id for your database and collectionprivatestaticfinalStringDATABASE_ID = "TestDB";
privatestaticfinalStringCOLLECTION_ID = "TestCollection";
// We'll use Gson for POJO <=> JSON serialization for this sample.// Codehaus' Jackson is another great POJO <=> JSON serializer.privatestaticGsongson = newGson();
publicstaticvoidmain(String[] args) throwsDocumentClientException,
IOException {
// Instantiate a DocumentClient w/ your DocumentDB Endpoint and AuthKey.DocumentClientdocumentClient = newDocumentClient(END_POINT,
MASTER_KEY, ConnectionPolicy.GetDefault(),
ConsistencyLevel.Session);
// Start from a clean state (delete database in case it already exists).try {
documentClient.deleteDatabase("dbs/" + DATABASE_ID, null);
}
catch (Exceptione) {
System.out.println(e.getMessage());
}
// Define a new database using the id above.DatabasemyDatabase = newDatabase();
myDatabase.setId(DATABASE_ID);
// Create a new database.myDatabase = documentClient.createDatabase(myDatabase, null)
.getResource();
System.out.println("Created a new database:");
System.out.println(myDatabase.toString());
System.out.println("Press any key to continue..");
System.in.read();
// Define a new collection using the id above.DocumentCollectionmyCollection = newDocumentCollection();
myCollection.setId(COLLECTION_ID);
// Set the provisioned throughput for this collection to be 1000 RUs.RequestOptionsrequestOptions = newRequestOptions();
requestOptions.setOfferThroughput(1000);
// Create a new collection.myCollection = documentClient.createCollection(
"dbs/" + DATABASE_ID, myCollection, requestOptions)
.getResource();
System.out.println("Created a new collection:");
System.out.println(myCollection.toString());
System.out.println("Press any key to continue..");
System.in.read();
// Create an object, serialize it into JSON, and wrap it into a// document.SomePojoallenPojo = newSomePojo("123", "Allen Brewer", "allen [at] contoso.com");
StringallenJson = gson.toJson(allenPojo);
DocumentallenDocument = newDocument(allenJson);
// Create the 1st document.allenDocument = documentClient.createDocument(
"dbs/" + DATABASE_ID + "/colls/" + COLLECTION_ID, allenDocument, null, false)
.getResource();
System.out.println("Created 1st document:");
System.out.println(allenDocument.toString());
System.out.println("Press any key to continue..");
System.in.read();
// Create another object, serialize it into JSON, and wrap it into a// document.SomePojolisaPojo = newSomePojo("456", "Lisa Andrews",
"lisa [at] contoso.com");
StringsomePojoJson = gson.toJson(lisaPojo);
DocumentlisaDocument = newDocument(somePojoJson);
// Create the 2nd document.lisaDocument = documentClient.createDocument(
"dbs/" + DATABASE_ID + "/colls/" + COLLECTION_ID, lisaDocument, null, false)
.getResource();
System.out.println("Created 2nd document:");
System.out.println(lisaDocument.toString());
System.out.println("Press any key to continue..");
System.in.read();
// Query documentsList<Document> results = documentClient
.queryDocuments(
"dbs/" + DATABASE_ID + "/colls/" + COLLECTION_ID,
"SELECT * FROM myCollection WHERE myCollection.email = 'allen [at] contoso.com'",
null).getQueryIterable().toList();
System.out.println("Query document where e-mail address = 'allen [at] contoso.com':");
System.out.println(results.toString());
System.out.println("Press any key to continue..");
System.in.read();
// Replace Document Allen with PercyallenPojo = gson.fromJson(results.get(0).toString(), SomePojo.class);
allenPojo.setName("Percy Bowman");
allenPojo.setEmail("Percy Bowman [at] contoso.com");
allenDocument = documentClient.replaceDocument(
allenDocument.getSelfLink(),
newDocument(gson.toJson(allenPojo)), null)
.getResource();
System.out.println("Replaced Allen's document with Percy's contact information");
System.out.println(allenDocument.toString());
System.out.println("Press any key to continue..");
System.in.read();
// Delete Percy's DocumentdocumentClient.deleteDocument(allenDocument.getSelfLink(), null);
System.out.println("Deleted Percy's document");
System.out.println("Press any key to continue..");
System.in.read();
// Delete DatabasedocumentClient.deleteDatabase("dbs/" + DATABASE_ID, null);
System.out.println("Deleted database");
System.out.println("Press any key to continue..");
System.in.read();
}
}The sample code above depends on a sample Plain Old Java Object (POJO) class, which is defined as follows:
classSomePojo {
privateStringid;
privateStringname;
privateStringemail;
publicSomePojo(Stringid, Stringname, Stringemail) {
super();
this.id = id;
this.name = name;
this.email = email;
}
publicStringgetEmail() {
returnemail;
}
publicStringgetId() {
returnid;
}
publicStringgetName() {
returnname;
}
publicvoidsetEmail(Stringemail) {
this.email = email;
}
publicvoidsetId(Stringid) {
this.id = id;
}
publicvoidsetName(Stringname) {
this.name = name;
}
}The following code Illustrates how to create a partitioned collection and use the partition key to access documents:
// Create a partition key definition that specifies the path to the property// within a document that is used as the partition key. PartitionKeyDefinitionpartitionKeyDef = newPartitionKeyDefinition();
ArrayList<String> paths = newArrayList<String>();
paths.add("/id");
partitionKeyDef.setPaths(paths);
// Create a collection with the partition key definition and set the offer throughput// to 10100 RU per second.DocumentCollectionmyPartitionedCollection = newDocumentCollection();
myPartitionedCollection.setId(COLLECTION_ID_PARTITIONED);
myPartitionedCollection.setPartitionKey(partitionKeyDef);
RequestOptionsoptions = newRequestOptions();
options.setOfferThroughput(10100);
myPartitionedCollection = documentClient.createCollection(
myDatabase.getSelfLink(), myCollection, options).getResource();
// Insert a document into the created collection.Stringdocument = "{ 'id': 'document1', 'description': 'this is a test document.' }";
DocumentnewDocument = newDocument(document);
newDocument = documentClient.createDocument(myPartitionedCollection.getSelfLink(),
newDocument, null, false).getResource();
// Read the created document, specifying the required partition key in RequestOptions.options = newRequestOptions();
options.setPartitionKey(newPartitionKey("document1"));
newDocument = documentClient.readDocument(newDocument.getSelfLink(), options).getResource();Additional samples are provided in the unit tests.
Be sure to check out the Microsoft Azure Developer Forums on MSDN or the Developer Forums on Stack Overflow if you have trouble with the provided code.
If you would like to become an active contributor to this project please follow the instructions provided in Azure Projects Contribution Guidelines.
If you encounter any bugs with the library please file an issue in the Issues section of the project.