NoSQL tutorial: Build a SQL API Java console application

Welcome to the NoSQL tutorial for the SQL API for Azure Cosmos DB Java SDK! After following this tutorial, you'll have a console application that creates and queries Azure Cosmos DB resources.

We cover:

  • Creating and connecting to an Azure Cosmos DB 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 an Azure Cosmos DB account

Let's create an Azure Cosmos DB 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 Azure Cosmos DB Emulator, follow the steps at Azure Cosmos DB Emulator to set up the emulator and skip ahead to Clone the GitHub project.

  1. Sign in to the Azure portal.

  2. Select Create a resource > Databases > Azure Cosmos DB.

    The Azure portal Databases pane

  3. On the Create Azure Cosmos DB Account page, enter the basic settings for the new Azure Cosmos account.

    Setting Value Description
    Subscription Subscription name Select the Azure subscription that you want to use for this Azure Cosmos account.
    Resource Group Resource group name Select a resource group, or select Create new, then enter a unique name for the new resource group.
    Account Name Enter a unique name Enter a name to identify your Azure Cosmos account. Because documents.azure.com is appended to the ID that you provide to create your URI, use a unique ID.

    The ID can only contain lowercase letters, numbers, and the hyphen (-) character. It must be between 3-31 characters in length.
    API Core (SQL) The API determines the type of account to create. Azure Cosmos DB provides five APIs: Core (SQL) and MongoDB for document data, Gremlin for graph data, Azure Table, and Cassandra. Currently, you must create a separate account for each API.

    Select Core (SQL) to create a document database and query by using SQL syntax.

    Learn more about the SQL API.
    Location Select the region closest to your users Select a geographic location to host your Azure Cosmos DB account. Use the location that is closest to your users to give them the fastest access to the data.

    The new account page for Azure Cosmos DB

  4. Select Review + create. You can skip the Network and Tags sections.

  5. Review the account settings, and then select Create. It takes a few minutes to create the account. Wait for the portal page to display Your deployment is complete.

    The Azure portal Notifications pane

  6. Select Go to resource to go to the Azure Cosmos DB account page.

    The Azure Cosmos DB account page

Step 2: Clone the GitHub project

You can get started by cloning the GitHub repository for Get Started with Azure Cosmos DB and Java. For example, from a local directory run the following to retrieve the sample project locally.

git clone git@github.com:Azure-Samples/azure-cosmos-db-documentdb-java-getting-started.git

cd azure-cosmos-db-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 Cosmos DB like creating documents and querying data within a collection. The pom.xml includes a dependency on the Azure Cosmos DB Java SDK on Maven.

<dependency>
    <groupId>com.microsoft.azure</groupId>
    <artifactId>azure-documentdb</artifactId>
    <version>LATEST</version>
</dependency>

Step 3: Connect to an Azure Cosmos DB account

Next, head back to the Azure portal to retrieve your endpoint and primary master key. The Azure Cosmos DB endpoint and primary key are necessary for your application to understand where to connect to, and for Azure Cosmos DB to trust your application's connection.

In the Azure portal, navigate to your Azure Cosmos DB account, and then click Keys. Copy the URI from the portal and paste it into https://FILLME.documents.azure.com in the Program.java file. Then copy the PRIMARY KEY from the portal and paste it into FILLME.

this.client = new DocumentClient(
    "https://FILLME.documents.azure.com",
    "FILLME"
    , new ConnectionPolicy(),
    ConsistencyLevel.Session);

Screenshot of the Azure portal used by the NoSQL tutorial to create a Java console application. Shows an Azure Cosmos DB account, with the ACTIVE hub highlighted, the KEYS button highlighted on the Azure Cosmos DB account blade, and the URI, PRIMARY KEY and SECONDARY KEY values highlighted on the Keys blade

Step 4: Create a database

Your Azure Cosmos DB 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");

// Azure Cosmos DB 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 Azure Cosmos DB'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 Azure Cosmos DB resources

Azure Cosmos DB supports rich queries against JSON documents stored in each collection. The following sample code shows how to query documents in Azure Cosmos DB 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

Azure Cosmos DB 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, Azure Cosmos DB 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, navigate to the project folder and compile using Maven:

mvn package

Running mvn package downloads the latest Azure Cosmos DB 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