NoSQL tutorial: Build a SQL API Java console application

Tip

The Azure Cosmos DB DocumentDB API or SQL (DocumentDB) API is now known as Azure Cosmos DB SQL API. You don't need to change anything to continue running your apps built with DocumentDB API. The functionality remains the same.

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. In a new browser window, sign in to the Azure portal.
  2. Click Create a resource > Databases > Azure Cosmos DB.

    The Azure portal Databases pane

  3. In the New account page, enter the settings for the new Azure Cosmos DB account.

    Setting Suggested value Description
    ID Enter a unique name Enter a unique name to identify this Azure Cosmos DB account. Because documents.azure.com is appended to the ID that you provide to create your URI, use a unique but identifiable ID.

    The ID can contain only lowercase letters, numbers, and the hyphen (-) character, and it must contain 3 to 50 characters.
    API SQL The API determines the type of account to create. Azure Cosmos DB provides five APIs to suits the needs of your application: SQL (document database), Gremlin (graph database), MongoDB (document database), Azure Table, and Cassandra, each which currently require a separate account.

    Select SQL because in this quickstart you are creating a document database that is queryable using SQL syntax and accessible with the SQL API.

    Learn more about the SQL API
    Subscription Your subscription Select Azure subscription that you want to use for this Azure Cosmos DB account.
    Resource Group Create new

    Then enter the same unique name as provided above in ID
    Select Create New, then enter a new resource-group name for your account. For simplicity, you can use the same name as your ID.
    Location Select the region closest to your users Select geographic location in which to host your Azure Cosmos DB account. Use the location that's closest to your users to give them the fastest access to the data.
    Enable geo-redundancy Leave blank This creates a replicated version of your database in a second (paired) region. Leave this blank.
    Pin to dashboard Select Select this box so that your new database account is added to your portal dashboard for easy access.

    Then click Create.

    The new account page for Azure Cosmos DB

  4. The account creation takes a few minutes. During account creation the portal displays the Deploying Azure Cosmos DB tile on the right side, you may need to scroll right on your dashboard to see the tile. There is also a progress bar displayed near the top of the screen. You can watch either area for progress.

    The Azure portal Notifications pane

    Once the account is created, the Congratulations! Your Azure Cosmos DB account was created page is displayed.

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

Screen shot 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