Skip to content

Latest commit

 

History

History
192 lines (142 loc) · 10.8 KB

documentdb-java-get-started.md

File metadata and controls

192 lines (142 loc) · 10.8 KB
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

NoSQL tutorial: Build a DocumentDB Java console application

[!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!

Prerequisites

Make sure you have the following:

Step 1: Create a DocumentDB account

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]

Step 2: Clone the Github project

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>

Step 3: Connect to a DocumentDB account

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);

Screen shot of the Azure Portal used by the NoSQL tutorial to create a Java console application. Shows a DocumentDB account, with the ACTIVE hub highlighted, the KEYS button highlighted on the DocumentDB account blade, and the URI, PRIMARY KEY and SECONDARY KEY values highlighted on the Keys blade

Step 4: Create a database

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);

Step 5: Create a collection

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);

Step 6: Create JSON documents

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);

Diagram illustrating the hierarchical relationship between the account, the online database, the collection, and the documents used by the NoSQL tutorial to create a Java console application

Step 7: Query DocumentDB resources

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

Step 8: Replace JSON document

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);

Step 9: Delete JSON document

Similarly, DocumentDB supports deleting JSON documents using the deleteDocument method.

this.client.delete("/dbs/familydb/colls/familycoll/docs/Andersen.1", null);

Step 10: Delete the database

Deleting the created database removes the database and all children resources (collections, documents, etc.).

this.client.deleteDatabase("/dbs/familydb", null);

Step 11: Run your Java console application all together!

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!

Next steps