Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork98
NoSQL embedded document store for Java
License
nitrite/nitrite-java
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
NOsqlObject (NO2 a.k.a Nitrite) database is an open source nosql embeddeddocument store. It supports both in-memory and file based persistent store.
Nitrite is an embedded database ideal for desktop, mobile or small web applications.
It features:
- Embedded, serverless
- Simple API
- Document-oriented
- Schemaless document collection and object repository
- Extensible storage engines - mvstore, rocksdb
- Indexing and full-text search
- Simple query api
- In-memory and file-based store
- Transaction support
- Schema migration support
- Encryption support
- Android compatibility (API Level 26)
Nitrite has a kotlin extension calledPotassium Nitrite for kotlin developers.Visithere for more details.
If you are looking for Nitrite for Flutter/Dart, head over tonitrite-flutter.
Nitrite DataGate and Nitrite Explorer is now deprecated and no longer maintained.
NOTE: There are breaking api changes in version 4.x. So please read theguide before upgrading from 3.x.x.
To use Nitrite in any Java application, first add the nitrite bill of materials, then add required dependencies:
Maven
<dependencyManagement> <dependencies> <dependency> <groupId>org.dizitart</groupId> <artifactId>nitrite-bom</artifactId> <version>[latest version]</version> <scope>import</scope> <type>pom</type> </dependency> </dependencies></dependencyManagement><dependencies> <dependency> <groupId>org.dizitart</groupId> <artifactId>nitrite</artifactId> </dependency> <dependency> <groupId>org.dizitart</groupId> <artifactId>nitrite-mvstore-adapter</artifactId> </dependency></dependencies>
Gradle
implementation(platform("org.dizitart:nitrite-bom:[latest version]")) implementation'org.dizitart:nitrite'implementation'org.dizitart:nitrite-mvstore-adapter'
A Todo android application is availablehere to demonstrate the usage of Nitrite in android.
Initialize Database
// create a mvstore backed storage moduleMVStoreModulestoreModule =MVStoreModule.withConfig() .filePath("/tmp/test.db") .compress(true) .build();// or a rocksdb based storage moduleRocksDBModulestoreModule =RocksDBModule.withConfig() .filePath("/tmp/test.db") .build();// initialization using builderNitritedb =Nitrite.builder() .loadModule(storeModule) .loadModule(newJacksonMapperModule())// optional .openOrCreate("user","password");
Create a Collection
// Create a Nitrite CollectionNitriteCollectioncollection =db.getCollection("test");// Create an Object RepositoryObjectRepository<Employee>repository =db.getRepository(Employee.class);
Annotations for POJO
@Entity(value ="retired-employee",// entity name (optional),indices = {@Index(value ="firstName",type =IndexType.NON_UNIQUE),@Index(value ="lastName",type =IndexType.NON_UNIQUE),@Index(value ="note",type =IndexType.FULL_TEXT),})publicclassEmployeeimplementsSerializable {// provides id field to uniquely identify an object inside an ObjectRepository@IdprivatelongempId;privateDatejoinDate;privateStringfirstName;privateStringlastName;privateStringnote;// ... public getters and setters}
CRUD Operations
// create a document to populate dataDocumentdoc =Document.createDocument("firstName","John") .put("lastName","Doe") .put("birthDay",newDate()) .put("data",newbyte[] {1,2,3}) .put("fruits",newArrayList<String>() {{add("apple");add("orange");add("banana"); }}) .put("note","a quick brown fox jump over the lazy dog");// insert the documentcollection.insert(doc);// find a documentcollection.find(where("firstName").eq("John").and(where("lastName").eq("Doe"));// update the documentcollection.update(where("firstName").eq("John"),createDocument("lastName","Wick"));// remove the documentcollection.remove(doc);// insert an object in repositoryEmployeeemp =newEmployee();emp.setEmpId(124589);emp.setFirstName("John");emp.setLastName("Doe");repository.insert(emp);
Create Indices
// create document indexcollection.createIndex(indexOptions(IndexType.NON_UNIQUE),"firstName","lastName");// compound indexcollection.createIndex(indexOptions(IndexType.FULL_TEXT),"note");// full-text index// create object index. It can also be provided via annotationrepository.createIndex(indexOptions(IndexType.NON_UNIQUE),"firstName");
Query a Collection
DocumentCursorcursor =collection.find(where("firstName").eq("John")// firstName == John .and(where("data").elemMatch("$".lt(4))// AND elements of data array is less than 4 .and(where("note").text("quick")// AND note field contains string 'quick' using full-text index ) ));for (Documentdocument :cursor) {// process the document}// get document by idDocumentdocument =collection.getById(nitriteId);// query an object repository and create the first resultCursor<Employee>cursor =repository.find(where("firstName").eq("John"));Employeeemployee =cursor.firstOrNull();
Transaction
try (Sessionsession =db.createSession()) {try (Transactiontransaction =session.beginTransaction()) {NitriteCollectiontxCol =transaction.getCollection("test");Documentdocument =createDocument("firstName","John");txCol.insert(document);transaction.commit(); }catch (TransactionExceptione) {transaction.rollback(); }}
Schema Migration
Migrationmigration1 =newMigration(Constants.INITIAL_SCHEMA_VERSION,2) {@Overridepublicvoidmigrate(InstructionSetinstructions) {instructions.forDatabase()// make a non-secure db to secure db .addUser("test-user","test-password");// create instructions for existing repositoryinstructions.forRepository(OldClass.class,"demo1")// rename the repository (in case of entity name changes) .renameRepository("migrated",null)// change datatype of field empId from String to Long and convert the values .changeDataType("empId", (TypeConverter<String,Long>)Long::parseLong)// change id field from uuid to empId .changeIdField(Fields.withNames("uuid"),Fields.withNames("empId"))// delete uuid field .deleteField("uuid")// rename field from lastName to familyName .renameField("lastName","familyName")// add new field fullName and add default value as - firstName + " " + lastName .addField("fullName",document ->document.get("firstName",String.class) +" " +document.get("familyName",String.class))// drop index on firstName .dropIndex("firstName")// drop index on embedded field literature.text .dropIndex("literature.text")// change data type of embedded field from float to integer and convert the values .changeDataType("literature.ratings", (TypeConverter<Float,Integer>)Math::round); }};Migrationmigration2 =newMigration(2,3) {@Overridepublicvoidmigrate(InstructionSetinstructions) {instructions.forCollection("test") .addField("fullName","Dummy Name"); }};MVStoreModulestoreModule =MVStoreModule.withConfig() .filePath("/temp/employee.db") .compressHigh(true) .build();db =Nitrite.builder() .loadModule(storeModule)// schema versioning is must for migration .schemaVersion(2)// add defined migration paths .addMigrations(migration1,migration2) .openOrCreate();
Import/Export Data
// Export data to json file// create export optionsExportOptionsexportOptions =newExportOptions();// set the nitrite factoryexportOptions.setNitriteFactory(() ->openDb("test.db"));// set the collections to exportexportOptions.setCollections(List.of("first"));// set the repositories to exportexportOptions.setRepositories(List.of("org.dizitart.no2.support.data.Employee","org.dizitart.no2.support.data.Company"));// set the keyed repositories to exportexportOptions.setKeyedRepositories(Map.of("key",Set.of("org.dizitart.no2.support.data.Employee")));// create an exporter with export optionsExporterexporter =Exporter.withOptions(exportOptions);exporter.exportTo("test.json");// Import data from the file// create import optionsImportOptionsimportOptions =newImportOptions();// set the nitrite factoryimportOptions.setNitriteFactory(() ->openDb("new-test.db"));// create an importer with import optionsImporterimporter =Importer.withOptions(importOptions);importer.importFrom("test.json");
More details are available in theguide.
Release notes are availablehere.
| Reference | API |
|---|---|
To build and test Nitrite, ensure you have JDK 11 (or higher) and Maven 3 installed.
git clone https://github.com/nitrite/nitrite-java.gitcd nitrite-javamvn clean installFor issues with, questions about, or feedback create adiscussion.
Think you’ve found a bug? Want to see a new feature in the Nitrite? Please open an issuehere. Butbefore you file an issue please check if it is already existing or not.
- Anindya Chatterjee
This project exists thanks to all the people who contribute. For more details please visitCONTRIBUTING.md.
Support this project by becoming a sponsor. Your logo will show up here with a link to your website.Become a sponsor for this project.
Idan Sheinberg has given a talk on Nitrite atKotlin Everywhere - TLV Edition meetup on October 27, 2019. Please find his presentationhere.
About
NoSQL embedded document store for Java
Topics
Resources
License
Contributing
Security policy
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Sponsor this project
Uh oh!
There was an error while loading.Please reload this page.
Packages0
Uh oh!
There was an error while loading.Please reload this page.


