NOsql Object (NO2 a.k.a Nitrite) database is an open source nosql embedded document store written in Java with MongoDB like API. It supports both in-memory and single file based persistent store.
<dependency>
<groupId>org.dizitart</groupId>
<artifactId>nitrite</artifactId>
<version>{version}</version>
</dependency>
Nitrite db = Nitrite.builder()
.compressed()
.filePath("/tmp/test.db")
.openOrCreate("user", "password");
// Create a Nitrite Collection
NitriteCollection collection = db.getCollection("test");
// create a document to populate data
Document doc = createDocument("firstName", "John")
.put("lastName", "Doe")
.put("birthDay", new Date())
.put("data", new byte[] {1, 2, 3})
.put("fruits", new ArrayList<String>() {{ add("apple"); add("orange"); }})
.put("note", "a quick brown fox jump over the lazy dog");
// insert the document
collection.insert(doc);
// update the document
collection.update(eq("firstName", "John"), createDocument("lastName", "Wick"));
Nitrite is a server-less embedded database ideal for desktop, mobile or small web applications. It is powered by MVStore engine of h2 database.
// create document index
collection.createIndex("firstName", indexOptions(IndexType.NonUnique));
collection.createIndex("note", indexOptions(IndexType.Fulltext));
Cursor cursor = collection.find(
// and clause
and(
// firstName == John
eq("firstName", "John"),
// elements of data array is less than 4
elemMatch("data", lt("$", 4)),
// elements of fruits list has one element matching orange
elemMatch("fruits", regex("$", "orange")),
// note field contains string 'quick' using full-text index
text("note", "quick")
)
);
for (Document document : cursor) {
// process the document
}
Nitrite database supports cross device synchronization via Nitrite DataGate server.
// connect to a DataGate server running at localhost 9090 port
DataGateClient dataGateClient = new DataGateClient("http://localhost:9090")
.withAuth("userId", "password");
DataGateSyncTemplate syncTemplate
= new DataGateSyncTemplate(dataGateClient, "remote-collection@userId");
// create sync handle
SyncHandle syncHandle = Replicator.of(db)
.forLocal(collection)
// a DataGate sync template implementation
.withSyncTemplate(syncTemplate)
// replication attempt delay of 1 sec
.delay(timeSpan(1, TimeUnit.SECONDS))
// both-way replication
.ofType(ReplicationType.BOTH_WAY)
// sync event listener
.withListener(new SyncEventListener() {
@Override
public void onSyncEvent(SyncEventData eventInfo) {
}
})
.configure();
// start sync in the background using handle
syncHandle.startSync();