DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
View Events Video Library
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Migrate, Modernize and Build Java Web Apps on Azure: This live workshop will cover methods to enhance Java application development workflow.

Modern Digital Website Security: Prepare to face any form of malicious web activity and enable your sites to optimally serve your customers.

Kubernetes in the Enterprise: The latest expert insights on scaling, serverless, Kubernetes-powered AI, cluster security, FinOps, and more.

E-Commerce Development Essentials: Considering starting or working on an e-commerce business? Learn how to create a backend that scales.

Related

  • Navigating NoSQL: A Pragmatic Approach for Java Developers
  • Jakarta NoSQL 1.0.0-b5: How To Make Your Life Easier Around Enterprise Java and NoSQL Databases
  • Architecture and Code Design, Pt. 2: Polyglot Persistence Insights To Use Today and in the Upcoming Years
  • Architecture and Code Design, Pt. 1: Relational Persistence Insights to Use Today and On the Upcoming Years

Trending

  • A Roadmap to True Observability
  • Mastering Backpressure in Java: Concepts, Real-World Examples, and Implementation
  • Harnessing the Power of APIs: Shaping Product Roadmaps and Elevating User Experiences through Authentication
  • Navigating Software Leadership in a Dynamic Era
  1. DZone
  2. Data Engineering
  3. Databases
  4. Nitrite: An Embedded NoSQL Database for Java and Android

Nitrite: An Embedded NoSQL Database for Java and Android

Nitrite is a serverless embedded database ideal for desktop, mobile, or small web applications. Learn the basics of it, how to install it, and how to use it.

Anindya Chatterjee user avatar by
Anindya Chatterjee
·
Apr. 27, 17 · Tutorial
Like (5)
Save
Tweet
Share
28.0K Views

Join the DZone community and get the full member experience.

Join For Free

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.

Features

  • 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 in any Java application, just add the below dependency:

Maven

<dependency>
    <groupId>org.dizitart</groupId>
    <artifactId>nitrite</artifactId>
    <version>1.0</version>
</dependency>

Gradle

compile 'org.dizitart:nitrite:1.0'

Usage

Let's now start with some quick examples.

Initialize Database

Nitrite db = Nitrite.builder()
        .compressed()
        .filePath("/tmp/test.db")
        .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

// Create a Nitrite Collection
NitriteCollection collection = db.getCollection("test");

// Create an Object Repository
ObjectRepository<Employee> repository = db.getRepository(Employee.class);

Construct a Document

// 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"); add("banana"); }})
     .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

// insert the document
collection.insert(doc);

// update the document
collection.update(eq("firstName", "John"), createDocument("lastName", "Wick"));

// remove the document
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.

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
}

// create document by id
Document document = collection.getById(nitriteId);

Nitrite supports indexing. It takes advantage of indexing during searching. More on this can be found here.

Replication

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.

// connect to a DataGate server 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();

We will discuss more on setting up a DataGate server in another article.

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.

Database Java (programming language) NoSQL Android (robot)

Opinions expressed by DZone contributors are their own.

Related

  • Navigating NoSQL: A Pragmatic Approach for Java Developers
  • Jakarta NoSQL 1.0.0-b5: How To Make Your Life Easier Around Enterprise Java and NoSQL Databases
  • Architecture and Code Design, Pt. 2: Polyglot Persistence Insights To Use Today and in the Upcoming Years
  • Architecture and Code Design, Pt. 1: Relational Persistence Insights to Use Today and On the Upcoming Years

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: