title | description | keywords | services | documentationcenter | author | manager | editor | ms.assetid | ms.service | ms.workload | ms.tgt_pltfrm | ms.devlang | ms.topic | ms.date | ms.author |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
NoSQL tutorial: Azure DocumentDB Java SDK | Microsoft Docs |
A NoSQL tutorial that creates an online database and Java console application using the DocumentDB Java SDK. Azure DocumentDB is a NoSQL database for JSON. |
nosql tutorial, online database, java console application |
documentdb |
Java |
arramac |
jhubbard |
monicar |
75a9efa1-7edd-4fed-9882-c0177274cbb2 |
documentdb |
data-services |
na |
java |
hero-article |
01/05/2017 |
arramac |
[!div class="op_single_selector"]
Welcome to the NoSQL tutorial for the Azure DocumentDB Java SDK! After following this tutorial, you'll have a console application that creates and queries DocumentDB resources.
We cover:
- Creating and connecting to a DocumentDB account
- Configuring your Visual Studio Solution
- Creating an online database
- Creating a collection
- Creating JSON documents
- Querying the collection
- Creating JSON documents
- Querying the collection
- Replacing a document
- Deleting a document
- Deleting the database
Now let's get started!
Make sure you have the following:
- An active Azure account. If you don't have one, you can sign up for a free account. Alternatively, you can use the Azure DocumentDB Emulator for this tutorial.
- Git
- Java Development Kit (JDK) 7+.
- Maven.
Let's create a DocumentDB account. If you already have an account you want to use, you can skip ahead to Clone the Github project. If you are using the DocumentDB Emulator, follow the steps at Azure DocumentDB Emulator to set up the emulator and skip ahead to Clone the Github project.
[!INCLUDE documentdb-create-dbaccount]
You can get started by cloning the Github repository for Get Started with DocumentDB and Java. For example, from a local directory run the following to retrieve the sample project locally.
git clone [email protected]:Azure-Samples/documentdb-java-getting-started.git
cd documentdb-java-getting-started
The directory contains a pom.xml
for the project and a src
folder containing Java source code including Program.java
which shows how perform simple operations with Azure DocumentDB like creating documents and querying data within a collection. The pom.xml
includes a dependency on the DocumentDB Java SDK on Maven.
<dependency>
<groupId>com.microsoft.azure</groupId>
<artifactId>azure-documentdb</artifactId>
<version>LATEST</version>
</dependency>
Next, head back to the Azure Portal to retrieve your endpoint and primary master key. The DocumentDB endpoint and primary key are necessary for your application to understand where to connect to, and for DocumentDB to trust your application's connection.
In the Azure Portal, navigate to your DocumentDB account, and then click Keys. Copy the URI from the portal and paste it into <your endpoint URI>
in the Program.java file. Then copy the PRIMARY KEY from the portal and paste it into <your key>
.
this.client = new DocumentClient(
"<your endpoint URI>",
"<your key>"
, new ConnectionPolicy(),
ConsistencyLevel.Session);
Your DocumentDB database can be created by using the createDatabase method of the DocumentClient class. A database is the logical container of JSON document storage partitioned across collections.
Database database = new Database();
database.setId("familydb");
this.client.createDatabase(database, null);
Warning
createCollection creates a new collection with reserved throughput, which has pricing implications. For more details, visit our pricing page.
A collection can be created by using the createCollection method of the DocumentClient class. A collection is a container of JSON documents and associated JavaScript application logic.
DocumentCollection collectionInfo = new DocumentCollection();
collectionInfo.setId("familycoll");
// DocumentDB collections can be reserved with throughput specified in request units/second.
// Here we create a collection with 400 RU/s.
RequestOptions requestOptions = new RequestOptions();
requestOptions.setOfferThroughput(400);
this.client.createCollection("/dbs/familydb", collectionInfo, requestOptions);
A document can be created by using the createDocument method of the DocumentClient class. Documents are user-defined (arbitrary) JSON content. We can now insert one or more documents. If you already have data you'd like to store in your database, you can use DocumentDB's Data Migration tool to import the data into a database.
// Insert your Java objects as documents
Family andersenFamily = new Family();
andersenFamily.setId("Andersen.1");
andersenFamily.setLastName("Andersen")
// More initialization skipped for brevity. You can have nested references
andersenFamily.setParents(new Parent[] { parent1, parent2 });
andersenFamily.setDistrict("WA5");
Address address = new Address();
address.setCity("Seattle");
address.setCounty("King");
address.setState("WA");
andersenFamily.setAddress(address);
andersenFamily.setRegistered(true);
this.client.createDocument("/dbs/familydb/colls/familycoll", family, new RequestOptions(), true);
DocumentDB supports rich queries against JSON documents stored in each collection. The following sample code shows how to query documents in DocumentDB using SQL syntax with the queryDocuments method.
FeedResponse<Document> queryResults = this.client.queryDocuments(
"/dbs/familydb/colls/familycoll",
"SELECT * FROM Family WHERE Family.lastName = 'Andersen'",
null);
System.out.println("Running SQL query...");
for (Document family : queryResults.getQueryIterable()) {
System.out.println(String.format("\tRead %s", family));
}
DocumentDB supports updating JSON documents using the replaceDocument method.
// Update a property
andersenFamily.Children[0].Grade = 6;
this.client.replaceDocument(
"/dbs/familydb/colls/familycoll/docs/Andersen.1",
andersenFamily,
null);
Similarly, DocumentDB supports deleting JSON documents using the deleteDocument method.
this.client.delete("/dbs/familydb/colls/familycoll/docs/Andersen.1", null);
Deleting the created database removes the database and all children resources (collections, documents, etc.).
this.client.deleteDatabase("/dbs/familydb", null);
To run the application from the console, first compile using Maven:
mvn package
Running mvn package
downloads the latest DocumentDB library from Maven and produces GetStarted-0.0.1-SNAPSHOT.jar
. Then run the app by running:
mvn exec:java -D exec.mainClass=GetStarted.Program
Congratulations! You've completed this NoSQL tutorial and have a working Java console application!
- Want a Java web app tutorial? See Build a web application with Java using DocumentDB.
- Learn how to monitor a DocumentDB account.
- Run queries against our sample dataset in the Query Playground.
- Learn more about the programming model in the Develop section of the DocumentDB documentation page.