Nitrite


Source link: https://github.com/dizitart/nitrite-database

Nitrite Database

NOsql Object ( NO 2 a.k.a Nitrite) database is an open source nosql embedded document store written in Java. It has MongoDB like API. It supports both in-memory and single file based persistent store powered by MVStore engine of h2 database.

Nitrite is a server-less embedded database ideal for desktop, mobile or small web applications.

It features:

  • Embedded key-value/document and object store

  • In-memory or single data file

  • Very fast and lightweight MongoDB like API

  • Indexing

  • Full text search capability

  • Full Android compatibility

  • Observable store

  • Both way replication via Nitrite DataGate server

Getting Started

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>{
version
}
</version> </dependency>

Gradle

compile 'org.dizitart:nitrite:{
version
}
'

Quick Examples

Initialize Database

//java initialization Nitrite db = Nitrite.builder()

.compressed()

.filePath("/tmp/test.db")

.openOrCreate("user", "password");
  //android initialization Nitrite db = Nitrite.builder()

.compressed()

.filePath(getFilesDir().getPath() + "/test.db")

.openOrCreate("user", "password");

Create a Collection

// Create a Nitrite Collection NitriteCollection collection = db.getCollection("test");
  // Create an Object Repository ObjectRepository<Employee> repository = db.getRepository(Employee.class);

Annotations for POJO

// provides index information for ObjectRepository @Indices({

@Index(field = "joinDate", type = IndexType.NonUnique),

@Index(field = "name", type = IndexType.Unique) 
}
) public class Employee implements Serializable {

  // provides id field to uniquely identify an object inside an ObjectRepository
  @Id
  private long empId;

private Date joinDate;

private String name;

private String address;

// ... public getters and setters 
}

CRUD Operations

// 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");
  // insert the document collection.insert(doc);
  // update the document collection.update(eq("firstName", "John"), createDocument("lastName", "Wick"));
  // remove the document collection.remove(doc);
// insert an object Employee emp = new Employee();
 emp.setEmpId(124589);
 emp.setFirstName("John");
 emp.setLastName("Doe");
  repository.insert(emp);

Create Indices

// create document index collection.createIndex("firstName", indexOptions(IndexType.NonUnique));
 collection.createIndex("note", indexOptions(IndexType.Fulltext));
  // create object index. It can also be provided via annotation repository.createIndex("firstName", indexOptions(IndexType.NonUnique));

Query a Collection

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);
  // query an object repository and create the first result Employee emp = repository.find(eq("firstName", "John"))

  .firstOrDefault();

Automatic Replication

// 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();

Import/Export Data

// Export data to a file Exporter exporter = Exporter.of(db);
 exporter.exportTo(schemaFile);
  //Import data from the file Importer importer = Importer.of(db);
 importer.importFrom(schemaFile);

More details are available in the reference document.

Release Notes

Release notes are available here.

Documentation

Reference API

Document

JavaDoc

Build

To build and test Nitrite

$ git clone https://github.com/dizitart/nitrite-database.git $ cd nitrite-database $ ./gradlew build

The test suite requires mongod to be running on localhost, listening on the default port. MongoDb is required to test replication using the DataGate server. Please run the below command to create the test user in mongo.

db.getSiblingDB('benchmark').createUser({
user: 'bench', pwd: 'bench', roles: [{
role: 'readWrite', db: 'benchmark'
}
, {
role: 'dbAdmin', db: 'benchmark'
}
]
}
)

The test suite also requires android sdk 24.4.1 to be installed and ANDROID_HOME environment variable to be setup properly to test the android example.

Support / Feedback

For issues with, questions about, or feedback talk to us at Gitter.

Bugs / Feature Requests

Think you’ve found a bug? Want to see a new feature in the Nitrite? Please open an issue here. But before you file an issue please check if it is already existing or not.

Maintainers

  • Anindya Chatterjee

Resources

A simple and easy android library to create your steps in modern view.

This is a wrapper that makes getting weather information from OpenWeatherMap a whole lot easier. What seperates this from other wrappers is that in addition to the basic weather information, it allows free openweathermap user to get up to 5 days of daily forecast information, which typically requires a developer account with OpenWeatherMap(180USD/month). Please note that this is not a hack, instead the library calculates the 3-hour forecast information that free users get, summarize those values, and return it as daily forecast.

Weather Android App using apixu API.

Matisse is a well-designed local image and video selector for Android. You can

  • Use it in Activity or Fragment
  • Select images including JPEG, PNG, GIF and videos including MPEG, MP4
  • Apply different themes, including two built-in themes and custom themes
  • Different image loaders
  • Define custom filter rules

Meepo is a retrofit-like router generator for Android. You can use it to create routers for Activities, Fragments and even any things.

Use multiple analytics and other trackers in your Application easily.

Topics


2D Engines   3D Engines   9-Patch   Action Bars   Activities   ADB   Advertisements   Analytics   Animations   ANR   AOP   API   APK   APT   Architecture   Audio   Autocomplete   Background Processing   Backward Compatibility   Badges   Bar Codes   Benchmarking   Bitmaps   Bluetooth   Blur Effects   Bread Crumbs   BRMS   Browser Extensions   Build Systems   Bundles   Buttons   Caching   Camera   Canvas   Cards   Carousels   Changelog   Checkboxes   Cloud Storages   Color Analysis   Color Pickers   Colors   Comet/Push   Compass Sensors   Conferences   Content Providers   Continuous Integration   Crash Reports   Credit Cards   Credits   CSV   Curl/Flip   Data Binding   Data Generators   Data Structures   Database   Database Browsers   Date &   Debugging   Decompilers   Deep Links   Dependency Injections   Design   Design Patterns   Dex   Dialogs   Distributed Computing   Distribution Platforms   Download Managers   Drawables   Emoji   Emulators   EPUB   Equalizers &   Event Buses   Exception Handling   Face Recognition   Feedback &   File System   File/Directory   Fingerprint   Floating Action   Fonts   Forms   Fragments   FRP   FSM   Functional Programming   Gamepads   Games   Geocaching   Gestures   GIF   Glow Pad   Gradle Plugins   Graphics   Grid Views   Highlighting   HTML   HTTP Mocking   Icons   IDE   IDE Plugins   Image Croppers   Image Loaders   Image Pickers   Image Processing   Image Views   Instrumentation   Intents   Job Schedulers   JSON   Keyboard   Kotlin   Layouts   Library Demos   List View   List Views   Localization   Location   Lock Patterns   Logcat   Logging   Mails   Maps   Markdown   Mathematics   Maven Plugins   MBaaS   Media   Menus   Messaging   MIME   Mobile Web   Native Image   Navigation   NDK   Networking   NFC   NoSQL   Number Pickers   OAuth   Object Mocking   OCR Engines   OpenGL   ORM   Other Pickers   Parallax List   Parcelables   Particle Systems   Password Inputs   PDF   Permissions   Physics Engines   Platforms   Plugin Frameworks   Preferences   Progress Indicators   ProGuard   Properties   Protocol Buffer   Pull To   Purchases   Push/Pull   QR Codes   Quick Return   Radio Buttons   Range Bars   Ratings   Recycler Views   Resources   REST   Ripple Effects   RSS   Screenshots   Scripting   Scroll Views   SDK   Search Inputs   Security   Sensors   Services   Showcase Views   Signatures   Sliding Panels   Snackbars   SOAP   Social Networks   Spannable   Spinners   Splash Screens   SSH   Static Analysis   Status Bars   Styling   SVG   System   Tags   Task Managers   TDD &   Template Engines   Testing   Testing Tools   Text Formatting   Text Views   Text Watchers   Text-to   Toasts   Toolkits For   Tools   Tooltips   Trainings   TV   Twitter   Updaters   USB   User Stories   Utils   Validation   Video   View Adapters   View Pagers   Views   Watch Face   Wearable Data   Wearables   Weather   Web Tools   Web Views   WebRTC   WebSockets   Wheel Widgets   Wi-Fi   Widgets   Windows   Wizards   XML   XMPP   YAML   ZIP Codes