Using the Java Driver for InterSystems IRIS Cloud Document
The InterSystems IRIS® Cloud Document driver for Java (com.intersystems.document) is an interface to the Cloud Document server that enables your Java application to work with Cloud Document databases, collections, and individual documents.
This document covers the following topics:
-
Connecting to the Cloud Document Server in Java describes how to create a pool of connections to the server.
-
Using Documents and Collections in Java demonstrates how to create and use a small collection of documents.
-
Querying Collections in Java demonstrates methods for querying documents in a Collection.
Connecting to the Cloud Document Server in Java
The document.DataSource class provides all connections between your Java application and the Cloud Document server. The DataSource object creates a pool of document.Connection objects, which are thin wrappers around jdbc.IRISConnection. This allows all database operations to share the same physical connection and transactional context with that of standard JDBC/SQL requests.
Before your application can connect to the Cloud Document server, you must have completed the following steps:
-
Complete the initial setup according to the instructions in Connecting Your Application to InterSystems IRIS Cloud DocumentOpens in a new tab. While in the InterSystems Cloud Services Portal, make note of the connection parameters in the Making External Connections table on the Deployment Overview page. You will need this information to establish a connection.
-
Add the InterSystems IRIS Cloud Document driver as a dependency to your development environment. You can download this driver from the InterSystems IRIS Driver PackagesOpens in a new tab page.
-
In your Java code, import the required libraries:
import com.intersystems.jdbc.*; import com.intersystems.document.*;
The following example creates a DataSource object. Replace the properties shown here with the ones shown on the Making External Connections table for your deployment (see step 1 above).
// Create an instance of DataSource and set the required properties
DataSource datasrc = DataSource.createDataSource();
datasrc.setServerName("your-hostname.elb.us-west-2.amazonaws.com");
datasrc.setPortNumber(443);
datasrc.setDatabaseName("USER");
datasrc.setUser("SQLAdmin");
datasrc.setPassword("!Test123");
datasrc.setConnectionSecurityLevel(10);
This DataSource will have a pool of ten connections (the default size). The actual connections are lazily created at the time the first getConnection() method is invoked, and will be available to service database requests at that point:
datasrc.getConnection();
System.out.println("\nDataSource pool size =" + datasrc.getSize());
In this example, getSize() returns the current pool size (which may be smaller than the actual pool size if there are any asynchronous requests pending).
Once you have established a connection, you can work with collections and individual documents as described in the following sections.
Using Documents and Collections in Java
The two main building blocks of a Cloud Document database are the Document and Collection classes:
-
Document objects contain data formatted as JSON objects and arrays. JSONObject and JSONArray are subclasses of Document that supply the methods to create and manipulate JSON structures.
-
Collection objects are containers for documents, and provide methods that allow documents to be inserted, retrieved, updated, and so forth.
The getCollection() method returns an existing Collection with the specified name, or creates a new collection if a collection with that name does not already exist. In this example, datasrc is a connected DataSource object (as demonstrated in Connecting to the Cloud Document Server in Java).
Collection testDocs = Collection.getCollection(datasrc,"testDocs");
if (testDocs.size() > 0) testDocs.drop(); // remove any existing documents
The Collection size() method returns the current number of documents in the collection. If the size is greater than 0, getCollection() has returned an already existing collection, and drop() is used to delete all of the old documents.
Document docOne = new JSONArray().add("Document #1");
One of the simplest ways to create a document is with the JSONArray add() method. New document docOne will contain a JSON array with only one element, but the add() method can be chained for longer arrays.
String id1 = testDocs.insert(docOne);
The Collection insert() method adds document docOne to the testDocs collection and returns string id1 containing the automatically generated document id (which will always be a numeric string).
System.out.println("\nCreated collection " + testDocs.getName());
System.out.println("Document content = " + testDocs.get("1").toJSONString());
The Collection get() method retrieves the Document with the specified id. In this example the id is a literal string, but id1 (returned by the call to insert()) could have been used instead. The Document toJSONString() method returns the contents of the document as a JSON string, and the following output is printed:
Created collection testDocs
Document content = ["Document #1"]
The JSONObject put() method accepts a key/value pair to create an object property. New document docTwo will contain a JSON object with two properties, name and age.
Document docTwo = new JSONObject()
.put("name","John Doe").put("age",42);
String id2 = testDocs.insert(docTwo);
The insert() method adds the document to the testDocs collection and returns string id2 containing the document id string.
System.out.println("\nCollection " + testDocs.getName() +
" now contains " + testDocs.size() + " documents:");
System.out.println(" id1: " + testDocs.get(id1).toJSONString() );
System.out.println(" id2: " + testDocs.get(id2).toJSONString() +"\n");
Strings id2 and id1 (created in the previous example) are used to retrieve and print the contents of the documents:
Collection testDocs now contains 2 documents:
id1: ["Document #1"]
id2: {"name":"John Doe","age":42}
The insert() method also accepts a list of Document objects. Two JSONObject documents are created here, but the list could contain objects of both Document subclasses:
java.util.List<Document> objectList = new java.util.ArrayList<>();
objectList.add(new JSONObject()
.put("name","Jane Doe").put("age",20));
objectList.add(new JSONObject()
.put("name","Anne Elk").put("age",38));
BulkResponse bulk = testDocs.insert(objectList);
By default, insert() automatically assigns an id to each element in the document array. The BulkResponse object contains a list of ids corresponding to the list of documents inserted, and provides a getIds() method to return them.
System.out.println("\nNewly inserted documents:");
for (String id : bulk.getIds()) {
Document currentDoc = testDocs.get(id);
System.out.println(" id" + id + ": " + currentDoc.toJSONString());
}
In the loop, each document is retrieved by id and printed:
Newly inserted documents:
id3: {"name":"Jane Doe","age":20}
id4: {"name":"Anne Elk","age":38}
The Collection getAll() method returns all documents in the collection:
java.util.List<Document> allDocuments = testDocs.getAll();
for (Document nextDoc : allDocuments) {
System.out.println(nextDoc.getID() + ": " + nextDoc.toJSONString());
};
System.out.println("\nCollection " + testDocs.getName() +
" contains " + testDocs.size() + " documents:");
This example uses Document getID() to retrieve the id of each document.
1: {"expires":"never","name":"First document","age":0}
2: {"name":"John Doe","age":42}
3: {"name":"Jane Doe","age":20}
4: {"name":"Anne Elk","age":38}
Collection testDocs contains 4 documents:
Querying Collections in Java
The Query and ShorthandQuery classes are both used to declare, prepare and execute queries:
-
A Query object is created by passing a query string to Collection.createQuery().
-
A ShorthandQuery object is created by passing a query string to Collection.createShorthandQuery(). Shorthand query text is simply a WHERE clause without the keyword WHERE.
A Cursor object is returned when either type of query object invokes execute(), The Cursor class implements and extends java.util.Iterator, containing various methods for iterating over the query result set.
The following examples demonstrate both query classes.
The easiest way to query a collection is with ShorthandQuery, which constructs the full SQL query for a given collection. The text of a shorthand query text is essentially a WHERE clause without the keyword WHERE. For example:
// Retrieve documents with ShorthandQuery
String shortQueryText="name > 'h' AND age > 21";
ShorthandQuery shortQuery = testDocs.createShorthandQuery(shortQueryText);
Cursor shortResults = shortQuery.execute();;
When execute() is called it returns a Cursor object that allows you to iterate through the query results:
System.out.println("\nShorthand query returned " + shortResults.count() + " results.");
while (shortResults.hasNext()) {
System.out.println(shortResults.next().toJSONString()); }
This prints the following result set:
Shorthand query returned 1 results.
{"_sourceID":2,"_sourceVersion":2,"content":{"name":"John Doe","age":42}}
Collections are always queried through a SQL interface and leverage the JSON_TABLE function, which maps dynamic JSON-like structure into a virtual table that can be accessed within your SQL query. This example uses JSON_TABLE to specify the target table.
// Retrieve documents with Query and JSON_TABLE
String queryText =
"SELECT * " +
"FROM JSON_TABLE('testDocs', '$' %TYPE 'testDocs[*]') " +
"WHERE name > ? AND age > 21";
Query query = testDocs.createQuery(queryText);
In this example, the first parameter in the WHERE statement is defined with method setParameter(). This method can also be used in shorthand queries.
query.clearParameters().setParameter(0, "a");
Cursor results = query.execute();
When execute() is called, it returns a Cursor object that allows you to iterate through the query results. This query returns the following result sets:
Full query returned 2 results.
{"expires":"","name":"John Doe","_documentVersion":"2","id":2,"_documentID":"2","age":"42"}
{"expires":"","name":"Anne Elk","_documentVersion":"5","id":4,"_documentID":"4","age":"38"}
To learn about all the options that the JSON_TABLE function provides, see the official JSON_TABLE documentation.