Skip to main content

Using Document Database with Java

The InterSystems IRIS® Document Database driver for Java (com.intersystems.document) is an interface to Document Database on the server that enable you to work with Document Databases, collections, and individual documents.

Connecting to the Database

This section demonstrates document.DataSource method createDataSource() and Collection method getConnection().

Get a Database Handle: createDataSource()

The database handle is the entry point for using the document data model in all client driver implementations. In Java, the database handle is a DataSource:

DataSource datasrc = DataSource.createDataSource();
datasrc.setPortNumber(1972);
datasrc.setServerName("localhost");
datasrc.setDatabaseName("USER");
datasrc.setUser("_SYSTEM");
datasrc.setPassword("SYS");
System.out.println("\nCreated datasrc\n");

This creates a DataSource object with the default pool size (10). The actual connections are lazily created at the time the first getConnection() method is invoked. At that time, the pool of connections will be created and will be available to service database requests. Default pool size can by modified by

datasrc.preStart(2);
datasrc.getConnection();
System.out.println("\nDataSource 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).

Java Collections

This section demonstrates Collection methods getCollection(), drop(), size(), getAll()

Get a Collection: getCollection()

A collection is a container for Document Database documents. It is the primary interface for working with a Document Database. You do not have to explicitly create a collection. getCollection() creates the specified collection if that collection does not yet exist:

Collection collectedDocs = Collection.getCollection(datasrc,"collectionName");
Count Documents in a Collection: size()

To count the number of documents with a collection instance invoke the size() method:

long size = collectedDocs.size();
Iterate through the Documents in a Collection: getAll()

To iterate through all of the documents in a collection, invoke the getAll() method, then sequence through that iterator:

List<Document> allDocuments = collectedDocs.getAll();
allDocuments.stream().forEach(doc ->
   System.out.println(doc.toJSONString())
   );
Drop a Collection: drop()

Dropping a collection will delete the extent of the collection and its metadata, except index definitions. This deletes all documents in the collection, but does not delete the collection itself. Any object references to the collection will stay valid and you can continue to work with it (e.g. store new documents). To drop (delete) a collection invoke the drop() method:

collectedDocs.drop();

Java Documents and Transactions (Add/Create/Insert/Delete)

document.Document class serves as a base class for both JSONArray and JSONObject. Documents are the main building blocks in the Document API. They can be saved, retrieved, updated etc. to/from Document using the Collections class.

Insert a Document: insert()

Use the Collection.Insert() method to persist a Document object.

To insert a single document invoke the insert() method:

Document doc = new JSONObject().put("Rank",1);
collectedDocs.insert(doc);

To insert an array of elements as individual documents:

List<Document> topTwo = new ArrayList<>();
  topTwo.add(new JSONObject().put("Rank",1));
  topTwo.add(new JSONObject().put("Rank",2));
BulkResponse bulk = collectedDocs.insert(topTwo);

System.out.println("Newly inserted document ids:");
for (String id : bulk.getIds())
    {
     System.out.print(id + " ");
    }
Retrieve a Document by id: get()

To retrieve a document in a collection, invoke the get() method and specify the document’s integer id:

Document doc = collectedDocs.get("<id>");

where <id> is a quoted integer value (for example, Get("23").)

Delete a Document by id: remove()

To delete a document from a collection, invoke the remove() method and specify the document’s integer id:

collectedDocs.remove("<id>");
Update a Document by id: replace()

To update a document in a collection, invoke the replace() method and specify the document’s integer id and the new data value:

collectedDocs.replace("<id>",new JSONObject().put("Rank",4));
Insert or Update a Document by id: upsert()

To either insert a document (if it does not exist) or update the document (if it does exist), invoke the upsert() method and specify the document’s integer id and the new data value:

Document upsertDoc = new JSONObject().put("Rank",1);
String upsertId = collectedDocs.upsert(upsertDoc);

Index and Query Java Collections

Create or change an Index: createIndex()

To create an index to documents in a collection, invoke the createIndex() method and specify an index name and an index request object. The index request object must be JSON encoded. It can be simple or complex. To create a simple index, set the property “key” to the JSON path that you want to index. The default index type is bitmap. The following example creates an index:

collectedDocs.createIndex("indexName","{\"key\":\"HomeCity\"}");

If the specified index name already exists, createIndex() will redefine this index with the new index definition.

Delete an Index: dropIndex()

To delete an index to documents in a collection, invoke the dropIndex() method and specify an existing index name:

collectedDocs.dropIndex("indexName");

If the specified index name does not exist, dropIndex() performs no operation and does not return an error.

Query a Collection: createQuery()

To query an instance of a collection, invoke the createQuery() method that specifies the SELECT query. You then issue an execute() method that executes the query and creates a cursor that allows you to iterate through the query result set:

Query querySlams = collectedDocs.createQuery(
           "select Rank,\"First Name\",\"Last Name\",Country,Points,
            \"Grand Slams\" from JSON_TABLE(('ATPList'),
            ('{\"columns\":\"ATPList[*]\"}'))");
Cursor slamCursor = querySlams.execute();
System.out.println("Executed query on ATPList - results follow: ");
List<Document> slamList = slamCursor.getAll();
slamList.forEach(doc -> System.out.println(doc.toJSONString()));
FeedbackOpens in a new tab