Querying in OJAI Applications
To query MapR-DB JSON tables in your OJAI
applications, you use the OJAI Query
interface. The typical flow of
your application involves creating a connection, obtaining a handle to the MapR-DB JSON table you want to query, constructing the
query, performing the query, and then processing the results.
Description
The DocumentStore
interface includes a
Query
interface. The Query
interface allows you to build a query programmatically.
To construct an OJAI query, call the following methods in the
Query
interface:
To run the query, pass the
Query
object to the DocumentStore.findQuery
method.
Table
interface is deprecated and replaced
by the OJAI version 2.0 DocumentStore
interface.Basic Application Flow
The following steps describe the basics in developing client applications that query MapR-DB JSON tables using the OJAI API.
- Create a Connection instance to your
MapR cluster using the DriverManager
class:
Connection connection = DriverManager.getConnection("ojai:mapr:");
NOTE: Do not omit the ending colon in the connection string. - Obtain a DocumentStore handle to a
MapR-DB JSON table
using the connection
object:
DocumentStore store = connection.getStore(tablePath);
- Create a Query object using the
connection
object:
Query query = connection.newQuery();
- Perform the query operation on the table:
DocumentStream stream = store.findQuery(query);
- Process the results.
The following code snippet iterates through the DocumentStream and prints each document as a JSON string:
for (final Document userDocument : stream) { // Print the OJAI Document System.out.println(userDocument.asJsonString()); }
To process individual fields within a document, use the DocumentReader interface. The following code snippet iterates through the fields in a document and prints the fields that are strings:Iterable it = stream.documentReaders(); for (DocumentReader reader : it) { EventType et = null; while ((et = reader.next()) != null) { if (et == EventType.STRING) { System.out.println("Value of field " + reader.getFieldName() + ": " + reader.getString()); } } }
- Close the stream, the connection to the document store, and the
connection to
MapR:
stream.close(); store.close; connection.close();
See Examples: Querying JSON Documents for complete code examples.