1. Are you ready for the Galaxy S20? Here is everything we know so far!

Nitrite: An Embedded NoSQL Database for Java and Android

Discussion in 'Android Development' started by Anindya Chatterjee, Jun 2, 2017.

  1. Anindya Chatterjee

    Thread Starter

    The NoSQL Object (or NO2, AKA Nitrite) database is an open-source NoSQL embedded document database written in Java with a MongoDB-like API. It supports both in-memory and single file-based persistent stores.

    Nitrite is a serverless embedded database ideal for desktop, mobile, or small web applications.

    • Embedded key-value/document and object stores.
    • In-memory or single data file.
    • Very fast and lightweight MongoDB-like API.
    • Indexing.
    • Full-text search capability.
    • Full Android compatibility.
    • Observable store.
    • Two-way replication via Nitrite DataGate server.
    Nitrite is not an RDBMS. It is also not a distributed NoSQL database like MongoDB or Cassandra. It does not have any server for external applications to connect to. It does not support sharding or ACID transaction.

    How to Install
    To use Nitrite just add the below dependency:


    Code (Java):
    1. compile 'org.dizitart:nitrite:1.0.1'

    Let's now start with some quick examples.

    Initialize Database

    Code (Java):
    1. Nitrite db = Nitrite.builder()
    2.         .compressed()
    3.         .filePath("/tmp/test.db")
    4.         .openOrCreate("user", "password");
    For more options on opening a database, visit here.

    Data in Nitrite is stored as a document in a collection called NitriteCollection. A document is nothing but a map of key-value pairs.

    A POJO can also be stored directly in an ObjectRepository. Under the hood, a POJO is converted into a document using Jackson's ObjectMapper and is stored in a NitriteCollection.

    Create a Collection

    Code (Java):
    1. // Create a Nitrite Collection
    2. NitriteCollection collection = db.getCollection("test");
    4. // Create an Object Repository
    5. ObjectRepository<Employee> repository = db.getRepository(Employee.class);
    Construct a Document

    Code (Java):
    1. // create a document to populate data
    3. Document doc = createDocument("firstName", "John")
    4.      .put("lastName", "Doe")
    5.      .put("birthDay", new Date())
    6.      .put("data", new byte[] {1, 2, 3})
    7.      .put("fruits", new ArrayList<String>() {{ add("apple"); add("orange"); add("banana"); }})
    8.      .put("note", "a quick brown fox jump over the lazy dog");
    CRUD operations are very easy and are very much similar to the Mongo Java API.

    Insert/Modify/Remove a Document

    Code (Java):
    1. // insert the document
    2. collection.insert(doc);
    4. // update the document
    5. collection.update(eq("firstName", "John"), createDocument("lastName", "Wick"));
    7. // remove the document
    8. collection.remove(doc);
    Details of CRUD operations for NitriteCollection can be found here for ObjectRepository here.

    Query a Collection
    Nitrite comes with an easy API for querying a collection efficiently.

    Code (Java):
    1. Cursor cursor = collection.find(
    2.                         // and clause
    3.                         and(
    4.                             // firstName == John
    5.                             eq("firstName", "John"),
    6.                             // elements of data array is less than 4
    7.                             elemMatch("data", lt("$", 4)),
    8.                             // elements of fruits list has one element matching orange
    9.                             elemMatch("fruits", regex("$", "orange")),
    10.                             // note field contains string 'quick' using full-text index
    11.                             text("note", "quick")
    12.                             )
    13.                         );
    15. for (Document document : cursor) {
    16.     // process the document
    17. }
    19. // create document by id
    20. Document document = collection.getById(nitriteId);
    Nitrite supports indexing. It takes advantage of indexing during searching. More on this can be found here.

    In our connected world, seamless replication over devices is a must. Nitrite supports replication with the help of Nitrite DataGate server. Setting up replication is very easy in Nitrite once a DataGate server instance is up and running.

    Code (Java):
    1. // connect to a DataGate server localhost 9090 port
    2. DataGateClient dataGateClient = new DataGateClient("http://localhost:9090")
    3.         .withAuth("userId", "password");
    5. DataGateSyncTemplate syncTemplate
    6.         = new DataGateSyncTemplate(dataGateClient, "remote-collection@userId");
    8. // create sync handle
    9. SyncHandle syncHandle = Replicator.of(db)
    10.         .forLocal(collection)
    11.         // a DataGate sync template implementation
    12.         .withSyncTemplate(syncTemplate)
    13.         // replication attempt delay of 1 sec
    14.         .delay(timeSpan(1, TimeUnit.SECONDS))
    15.         // both-way replication
    16.         .ofType(ReplicationType.BOTH_WAY)
    17.         // sync event listener
    18.         .withListener(new SyncEventListener() {
    19.             @Override
    20.             public void onSyncEvent(SyncEventData eventInfo) {
    22.             }
    23.         })
    24.         .configure();
    26. // start sync in the background using handle
    27. syncHandle.startSync();
    Further Reading
    There is a lot more to it and I can not squeeze everything into a single article. We will discuss those things in coming days. In the meantime, if you feel interested head out to the Nitrite's project page or GitHub repo. If you want to dig into Nitrite's capabilities in more details, please go to its documentation page, where you will find all the tiny details with lots of examples.

    sweetndreemy73 likes this.

    1. Download the Forums for Android™ app!



Share This Page