Nitrite Java Documentation

repository·main·Indexed 21 days ago

https://github.com/nitrite/nitrite-java

An open-source, embedded NoSQL object database for desktop, mobile, and small web applications. Nitrite provides a document-oriented, schemaless storage engine supporting in-memory and file-based persistence. It includes various modules such as the MVStore and RocksDB storage adapters, Jackson-based mapping via nitrite-jackson-mapper, spatial data support through nitrite-spatial, and data import/export utilities via nitrite-support. A Kotlin extension is also available via potassium-nitrite.

Tokens
10.7K
Snippets
36
Records
40
Agent score
75%

What's inside Nitrite

  1. Use Collections and Object Repositories

    main

    Nitrite provides two ways to interact with data:

    1. Collections: For schemaless Document objects.
    2. Object Repositories: For mapping POJOs (Plain Old Java Objects) to the database using annotations.
    // Create a Nitrite Collection
    NitriteCollection collection = db.getCollection("test");
    
    // Create an Object Repository
    ObjectRepository<Employee> repository = db.getRepository(Employee.class);
  2. Perform Schema Migrations

    main

    Nitrite allows you to define Migration objects to evolve your database schema. Migrations are applied during database initialization using .addMigrations(...). You must specify a .schemaVersion(int) in the builder for migrations to be active.

    Migration migration1 = new Migration(Constants.INITIAL_SCHEMA_VERSION, 2) {
        @Override
        public void migrate(InstructionSet instructions) {
            instructions.forDatabase()
                .addUser("test-user", "test-password");
    
            instructions.forRepository(OldClass.class, "demo1")
                .renameRepository("migrated", null)
                .changeDataType("empId", (TypeConverter<String, Long>) Long::parseLong)
                .changeIdField(Fields.withNames("uuid"), Fields.withNames("empId"))
                .deleteField("uuid")
                .renameField("lastName", "familyName")
                .addField("fullName", document -> document.get("firstName", String.class) + " "
                    + document.get("familyName", String.class))
                .dropIndex("firstName")
                .dropIndex("literature.text")
                .changeDataType("literature.ratings", (TypeConverter<Float, Integer>) Math::round);
        }
    };
    
    // ... (migration2 definition)
    
    // Applying migrations during initialization
    db = Nitrite.builder()
        .loadModule(storeModule)
        .schemaVersion(2)
        .addMigrations(migration1, migration2)
        .openOrCreate();
  3. Initialize the Spatial Module

    main

    To use spatial features, you must load the SpatialModule and a JacksonMapperModule configured with a GeometryModule when building your Nitrite instance. This ensures that spatial geometries are correctly serialized and deserialized.

    Nitrite db = Nitrite.builder()
            .loadModule(new JacksonMapperModule(new GeometryModule()))
            .loadModule(new SpatialModule())
            .openOrCreate();
  4. Install Nitrite Spatial

    main

    To enable spatial data support and spatial queries in Nitrite, add the nitrite-spatial dependency to your project using Maven or Gradle.

    <dependencies>
        <dependency>
            <groupId>org.dizitart</groupId>
            <artifactId>nitrite-spatial</artifactId>
        </dependency>
    </dependencies>
    implementation 'org.dizitart:nitrite-spatial'
  5. Install the Nitrite MVStore Storage Adapter

    main

    To use the MVStore-based NitriteStore implementation, add the nitrite-mvstore-adapter dependency to your project using Maven or Gradle.

    <!-- Maven -->
    <dependencies>
        <dependency>
            <groupId>org.dizitart</groupId>
            <artifactId>nitrite-mvstore-adapter</artifactId>
        </dependency>
    </dependencies>
    
    <!-- Gradle -->
    implementation 'org.dizitart:nitrite-mvstore-adapter'
  6. Export data to a JSON file

    main

    Use the Exporter class to save your Nitrite database contents to a JSON file. You must provide ExportOptions which include a NitriteFactory to initialize the database instance, and specify which collections, repositories, or keyed repositories should be included in the export.

    Key configuration methods for ExportOptions:

    • setNitriteFactory(Supplier<Nitrite>): Provides the logic to open/create the database instance.
    • setCollections(List<String>): Specifies the names of the collections to export.
    • setRepositories(List<String>): Specifies the class names of the repositories to export.
    • setKeyedRepositories(Map<String, Set<String>>): Specifies keyed repositories mapping a key to a set of class names.
    // export data to a json file
    ExportOptions exportOptions = new ExportOptions();
    exportOptions.setNitriteFactory(() -> {
        MVStoreModule storeModule = MVStoreModule.withConfig()
            .filePath("/tmp/test-old.db")
            .build();
        
        return Nitrite.builder()
            .compressed()
            .loadModule(storeModule)
            .openOrCreate();
    });
    exportOptions.setCollections(List.of("first"));
    exportOptions.setRepositories(List.of("org.dizitart.no2.support.data.Employee"));
    exportOptions.setKeyedRepositories(Map.of("key", Set.of("org.dizitart.no2.support.data.Employee")));
    
    Exporter exporter = Exporter.withOptions(exportOptions);
    exporter.exportTo(schemaFile);
  7. Initialize Nitrite Database with Kotlin DSL

    main

    Use the nitrite builder function to initialize a Nitrite database instance. This function leverages Kotlin's DSL capabilities to allow configuring modules (like storage engines, mappers, and indexers) within a trailing lambda block.

    Common modules to load include:

    • MVStoreModule(fileName): For file-based storage.
    • module(KNO2JacksonMapper()): For JSON mapping.
    • module(NitriteTextIndexer(UniversalTextTokenizer())): For text indexing.
    val db = nitrite("user", "password") {
        loadModule(MVStoreModule(fileName))
        loadModule(module(KNO2JacksonMapper()))
        loadModule(module(NitriteTextIndexer(UniversalTextTokenizer())))
    }
  8. Install the Nitrite RocksDB Storage Adapter

    main

    To use RocksDB as the underlying storage engine for your Nitrite database, add the nitrite-rocksdb-adapter dependency to your project using Maven or Gradle.

    <!-- Maven -->
    <dependencies>
        <dependency>
            <groupId>org.dizitart</groupId>
            <artifactId>nitrite-rocksdb-adapter</artifactId>
        </dependency>
    </dependencies>
    
    <!-- Gradle -->
    implementation 'org.dizitart:nitrite-rocksdb-adapter'
  9. Install Nitrite Jackson Mapper

    main

    To enable Jackson-based mapping in Nitrite, add the nitrite-jackson-mapper dependency to your project. This allows you to use Jackson to convert entity classes to and from Document and Object without writing manual EntityConverter implementations.

    <!-- Maven -->
    <dependencies>
        <dependency>
            <groupId>org.dizitart</groupId>
            <artifactId>nitrite-jackson-mapper</artifactId>
        </dependency>
    </dependencies>
    
    <!-- Gradle -->
    implementation 'org.dizitart:nitrite-jackson-mapper'
  10. Install Nitrite Database

    main

    To use Nitrite in a Java application, use the Nitrite Bill of Materials (BOM) to manage versions, then add the core nitrite dependency and your preferred storage adapter (e.g., nitrite-mvstore-adapter).

    ### 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
    
    ```groovy
    
    implementation(platform("org.dizitart:nitrite-bom:[latest version]"))
        
    implementation 'org.dizitart:nitrite'
    implementation 'org.dizitart:nitrite-mvstore-adapter'
    
  11. Install Nitrite Support via Maven or Gradle

    main

    To use the Nitrite Support library for importing and exporting data as JSON files, add the following dependency to your build configuration.

    <!-- Maven -->
    <dependencies>
        <dependency>
            <groupId>org.dizitart</groupId>
            <artifactId>nitrite-support</artifactId>
        </dependency>
    </dependencies>
    
    <!-- Gradle -->
    implementation 'org.dizitart:nitrite-support'
  12. Query spatial data using Intersect, Within, and Near filters

    main

    Nitrite Spatial provides three types of spatial filters for querying documents based on geometry:

    • Intersect Filter: Matches documents where the field's spatial data intersects the specified Geometry.
    • Within Filter: Matches documents where the field's spatial data is contained within the specified Geometry.
    • Near Filter: Matches documents where the field's spatial data is near a specific coordinate within a given distance.

    Note: These examples use WKTReader from the JTS library to parse Well-Known Text (WKT) into Geometry objects.

    // Intersect
    WKTReader reader = new WKTReader();
    Geometry search = reader.read("POLYGON ((490 490, 536 490, 536 515, 490 515, 490 490))");
    Cursor<SpatialData> cursor = repository.find(where("geometry").intersects(search));
    
    // Within
    Geometry searchWithin = reader.read("POLYGON ((490 490, 536 490, 536 515, 490 515, 490 490))");
    Cursor<SpatialData> cursorWithin = repository.find(where("geometry").within(searchWithin));
    
    // Near
    Point searchPoint = (Point) reader.read("POINT (490 490)");
    Cursor<SpatialData> cursorNear = repository.find(where("geometry").near(searchPoint, 20.0));