Oracle NoSQL Database Cloud Service – 15 Minutes to Hello World

March 31, 2020 | 8 minute read
Bob Rhubart
Community Manager, Oracle Groundbreakers Team
Text Size 100%:

Guest Post by:
Dave Rubin, Senior Director, NoSQL and Embedded Database Development, Oracle
Michael Brey, Director, Product Development

The Oracle NoSQL Database Development team is thrilled to have the Oracle NoSQL Database Cloud Service fully integrated on the native Oracle Cloud Infrastructure. 

In this post we will walk through the steps to write a simple Hello World application using the recently integrated Oracle NoSQL Database Cloud Service.  You will also see that writing your first Hello World application can be accomplished in 15 minutes or less.  You may first be wondering, why use a NoSQL Database and what is the Oracle NoSQL Database Cloud Service?  These are great questions and ones that we will discuss before getting into the code.

Why use a NoSQL Database?

Modern application developers have many choices when faced with deciding when and how to persist a piece of data.   In recent years, NoSQL databases have become increasingly popular and are now seen as one of the necessary tools in the toolbox that every application developer must have at their disposal.  While tried and true relational databases are great at solving classic application problems like data normalization, strictly consistent data, and arbitrarily complex queries to access that data, NoSQL databases take a different approach.  

Many of the more recent applications have been designed to personalize the user experience to the individual, ingest huge volumes of machine generated data, deliver blazingly fast, crisp user interface experiences, and deliver these experiences to large populations of concurrent users.  In addition, these applications must always be operational, with zero down-time, and with zero tolerance for failure.  The approach taken by Oracle NoSQL Database is to provide extreme availability and exceptionally predictable, single digit millisecond response times to simple queries at scale. The Oracle NoSQL Database Cloud Service is designed from the ground up for high availability, predictably fast responses, resiliency to failure, all while operating at extreme scale. Largely, this is due to Oracle NoSQL Database’s shared nothing, replicated, horizontal scale-out architecture and by using the Oracle NoSQL Database Cloud Service, Oracle manages the scale out, monitoring, tuning, and hardware/software maintenance, all while providing your application with predictable behavior.

Getting Started with the Oracle NoSQL Database Cloud Service

The Oracle NoSQL Database Cloud Service is a server-less, fully managed data store that delivers predictable single digit response times and allows application to scale on demand via provisioning API calls.  There are four simple steps to getting started with the Oracle NoSQL Database Cloud Service.

  • Download the Oracle NoSQL Database driver
  • Connect to the Oracle NoSQL Database Cloud Service
  • Create a table with provisioned reads/sec, writes/sec, and GB storage
  • Write data to the table and read data from the table

Furthermore, you can use your free cloud credits to do all of this and not pay a single penny. 

Once you have created a cloud account, you can either navigate to the Oracle NoSQL Database table management console, or if you are like most developers, quickly move onto writing your first hello world code.  For this release of the Oracle NoSQL Database Cloud Service, you can write your first hello world program using Python, Node.js, Java, or Go.  Future releases of the service will support C++, C#, and other popular programming languages.  I will use Java for the remainder of this blog.  Java 8 and Java 11 are certified.

Download the Oracle NoSQL Database Driver

Since access to the Oracle NoSQL Cloud Service is via HTTP, you can run your application directly on your laptop and connect to the database service over the internet.  While we would never recommend using the internet as a network transport for performance sensitive applications, it works perfectly for our hello world example.  In fact, most likely you would want to deploy by running your application inside your own tenancy co-located in the same Oracle Cloud Infrastructure region as your NoSQL table and use the Oracle Cloud Infrastructure Service Gateway to connect to the NoSQL Cloud Service.

Navigate to the following URL https://www.oracle.com/downloads/cloud/nosql-cloud-java-driver-downloads.html, where you're presented with the following options:

Choose the tar.gz file and download it.  Once you unbundle this file, you will see a lib directory which contains the Oracle NoSQL Cloud Service driver along with a few other dependent libraries.  For this example, place these files in /Users/drubin/NoSQL/oracle-nosql-java-sdk-5.2.11.  Notice the contents of the lib directory.  These are the only libraries that you will need to compile and run your hello world example.

Connect Application to the Oracle NoSQL Database Cloud Service

The Oracle NoSQL Database Cloud Service uses the Oracle Cloud Infrastructure native cloud Identity Access Manager (IAM) for authentication and authorization.  In the Javadoc (https://docs.oracle.com/en/cloud/paas/nosql-cloud/csnjv/index.html) for the driver, you will notice a new package entitled oracle.nosql.driver.iam, which currently contains a single class, SignatureProvider. We will use this class to provide our authentication information to the cloud service. 

Before you can authenticate your application with the cloud service, you must generate a key pair and upload your public key to the Oracle Cloud.  The instructions here will guide you through generating an API signing key and uploading the public key to the Oracle Cloud: https://docs.cloud.oracle.com/en-us/iaas/Content/API/Concepts/apisigningkey.htm#How

The following information will be needed for you to successfully authenticate with the cloud service:

The code below is structured as follows:

  1. The method getNoSQLConnection – This is where you will fill in your specific credentials. This method will perform authentication with the Oracle NoSQL Cloud Service and return a handle to the service.
  2. The method createHelloWorldTable - This method will create a table with two columns; an ID column of type LONG and a content column of type JSON.
  3. The method writeOneRecord – This method will write a single record to the hello world table.
  4. The method readOneRecord – This method will read a single record from the hello world table and return this record as a JSON string.
  5. The main() entrypoint – Will first get a connection to the service, create the table, write a single record, read that record back, and finally print that record to stdout.

import oracle.nosql.driver.NoSQLHandle;
import oracle.nosql.driver.NoSQLHandleConfig;
import oracle.nosql.driver.NoSQLHandleFactory;
import oracle.nosql.driver.Region;
import oracle.nosql.driver.iam.SignatureProvider;
import oracle.nosql.driver.ops.*;
import oracle.nosql.driver.values.JsonOptions;
import oracle.nosql.driver.values.MapValue;

import java.io.File;


public class HelloWorld {

    /**
     * Authenticate with the NoSQL cloud service
     *
     * @return A session handle to the NoSQL Database cloud service
     */
   
private static NoSQLHandle getNoSQLConnection() {

        SignatureProvider authProvider = new SignatureProvider(
                "Your tenant OCID goes here",
                "Your user OCID goes here",
                "Your key fingerprint goes here",
                new File("~/.oci/oci_api_key.pem"), // path to your private key file
               
"The pass phrase for your key goes here".toCharArray());

        /**

         * Use the Ashburn, US region in this example OR

         * Zurich, Switzerland by changing to Region.EU_ZURICH_1

         */
       
return(NoSQLHandleFactory.createNoSQLHandle(
                new NoSQLHandleConfig(Region.US_ASHBURN_1, authProvider)));

    }

    /**
     * Creates a table with two columns: An ID PK and some JSON content
     *
     * @param
serviceHandle Authenticated NoSQL Database cloud service handle
     *
     * @throws Exception on Unexpected table creation error
     */
   
private static void createHelloWorldTable(NoSQLHandle serviceHandle)

         throws Exception {
        TableRequest req = new TableRequest().setStatement(
                  "CREATE TABLE if not exists hello_world(id LONG, " +
                  "content JSON, primary key (id))");

        /**

         * Set the number of reads per sec to 25, writes per second to 25,

         * and GB storage to 25

         */
       
req.setTableLimits(new TableLimits(25, 25, 25));

        TableResult tr = serviceHandle.tableRequest(req);

       
/**

         * Table creation is async so wait for the table to become active

         * before returning.  This call will wait for a total of up to 2 minutes

         * for the table to become up and will check every 500 milliseconds

         * to see if the table has become active

         */
       
tr.waitForCompletion(serviceHandle, 120000, 500);


       
/

  * We waited long enough.  If the table is still not active then

  * something went wrong

  */
if (tr.getTableState() != TableResult.State.ACTIVE)  {
    throw new Exception("Unable to create table hello_world " +

                    tr.getTableState());
}

    }

    /**
     * Writes a single record to the "hello_world" table
     *
     * @param
serviceHandle Authenticated NoSQL Database cloud service handle
     * @param
id Primary key.  If the key exists, the record will be overwritten
     * @param
jsonContent The content to write
     */
   
private static void writeOneRecord(NoSQLHandle serviceHandle, long id,

                           String jsonContent) {
        MapValue value = new MapValue().put("id", id);

        MapValue contentVal = value.putFromJson("content", jsonContent,

                                     new JsonOptions());
        PutRequest putRequest = new PutRequest()
                .setValue(value)
                .setTableName("hello_world");
        serviceHandle.put(putRequest);
    }

    /**
     * Reads a single record from the "hello_world" table
     *
     * @param
serviceHandle Authenticated NoSQL Database cloud service handle
     * @param
id PK of the record to read
     * @return The JSON string containing the content of the requested record

     *         or null if the requested record does not exist
     */
   
private static String readOneRecord(NoSQLHandle serviceHandle, long id) {
        GetRequest getRequest = new GetRequest();
        getRequest.setKey(new MapValue().put("id", id));
        getRequest.setTableName("hello_world");

        long before = System.currentTimeMillis();
        GetResult gr = serviceHandle.get(getRequest);

        if (gr != null) {
            return (gr.getValue().toJson(new JsonOptions()));
        } else {
            return(null);
        }
    }

    public static void main (String args[]) {
        try {
            NoSQLHandle handle = getNoSQLConnection();
            createHelloWorldTable(handle);
            writeOneRecord(handle, 1, "{\"hello\":\"world\"}");
            System.out.println(readOneRecord(handle, 1));

             System.exit(0);
        } catch (Exception e) {
            e.printStackTrace();

            System.exit(-1);
        }
    }
}

 

If you take the code above and place it in a file entitled HelloWorld.java and you fill in your credentials in the getNoSQLConnection() method, you can compile this file as specified below:

and run the resulting class file as specified below (NOTE the JSON output from running the program):

    

Using the Native Oracle Cloud Infrastructure Console

You can also explore your tables using the Oracle Cloud Infrastructure console.  On the left hand menu, simply navigate to the NoSQL Database menu item.

Once you click on the hello_world table link, you will see the following page:

Clicking on the Table rows control and then the clicking the Run query button control will display the record that you just inserted into the table:

If you have questions regarding this exercise, please send an email to oraclenosql-info_ww@oracle.com with “Hello World” in the subject line, and someone will get back to you as soon as possible.

Bob Rhubart

Community Manager, Oracle Groundbreakers Team

Oracle Groundbreaker Team Community Manager Bob Rhubart is the host/engineer/producer of the Oracle Groundbreaker Podcast, producer of the 2 Minute Tech Tip video series, hosts Groundbreaker Live interviews with technology experts recorded at Oracle Code, Oracle OpenWorld, and other events, writes a regular column for Oracle Magazine, and manages the ACES in Action blog.


Previous Post

Announcing Oracle NoSQL Database Cloud Service

Bob Rhubart | 4 min read

Next Post


Protect Your Sensitive Data With Secrets In The Oracle Cloud

Todd Sharp | 5 min read