ZoneTree 1.8.4

Prefix Reserved
dotnet add package ZoneTree --version 1.8.4                
NuGet\Install-Package ZoneTree -Version 1.8.4                
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="ZoneTree" Version="1.8.4" />                
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add ZoneTree --version 1.8.4                
#r "nuget: ZoneTree, 1.8.4"                
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
// Install ZoneTree as a Cake Addin
#addin nuget:?package=ZoneTree&version=1.8.4

// Install ZoneTree as a Cake Tool
#tool nuget:?package=ZoneTree&version=1.8.4                

ZoneTree Logo

ZoneTree

ZoneTree is a persistent, high-performance, transactional, and ACID-compliant ordered key-value database for .NET. It operates seamlessly both in-memory and on local/cloud storage, making it an ideal choice for a wide range of applications requiring efficient data management.

License Downloads Platform Build

Table of Contents


Why Choose ZoneTree?

  1. Pure C# Implementation: ZoneTree is developed entirely in C#, ensuring seamless integration and deployment within .NET ecosystems without external dependencies.

  2. Exceptional Performance: Demonstrates performance several times faster than Facebook's RocksDB and hundreds of times faster than SQLite. Optimized for both speed and efficiency.

  3. Data Durability and Crash Resilience: Provides optional durability features that protect data against crashes and power outages, ensuring data integrity under all circumstances.

  4. Transactional and ACID-Compliant: Supports both transactional and non-transactional access with full ACID guarantees, offering flexibility for various application requirements.

  5. Embeddable Database Engine: Easily embed ZoneTree into applications, eliminating the overhead of maintaining or shipping separate database products.

  6. Scalability: Capable of handling small to massive datasets, allowing the creation of both scalable and non-scalable databases tailored to specific needs.


Performance

ZoneTree sets new standards in database performance, showcasing remarkable speeds in data insertion, loading, and iteration operations.

Benchmark Results

  • 100 Million integer key-value pairs inserted in 20 seconds using WAL mode = NONE.
  • Loading database with 100 million integer key-value pairs takes 812 milliseconds.
  • Iterating over 100 million key-value pairs completes in 24 seconds.

Detailed Benchmark for Various Modes:

Insert Benchmarks 1M 2M 3M 10M
int-int ZoneTree async-compressed WAL 267 ms 464 ms 716 ms 2693 ms
int-int ZoneTree sync-compressed WAL 834 ms 1617 ms 2546 ms 8642 ms
int-int ZoneTree sync WAL 2742 ms 5533 ms 8242 ms 27497 ms
str-str ZoneTree async-compressed WAL 892 ms 1833 ms 2711 ms 9443 ms
str-str ZoneTree sync-compressed WAL 1752 ms 3397 ms 5070 ms 19153 ms
str-str ZoneTree sync WAL 3488 ms 7002 ms 10483 ms 38727 ms
RocksDb sync WAL (10K ⇒ 11 sec) ~1,100,000 ms N/A N/A N/A
int-int RocksDb sync-compressed WAL 8059 ms 16188 ms 23599 ms 61947 ms
str-str RocksDb sync-compressed WAL 8215 ms 16146 ms 23760 ms 72491 ms

Full Benchmark Results

Benchmark Configuration:

DiskCompressionBlockSize = 10 * 1024 * 1024; // 10 MB
WALCompressionBlockSize = 32 * 1024 * 8;     // 256 KB
DiskSegmentMode = DiskSegmentMode.SingleDiskSegment;
MutableSegmentMaxItemCount = 1_000_000;
ThresholdForMergeOperationStart = 2_000_000;

Additional Notes:

  • ZoneTree has been tested successfully with up to 1 billion records on standard desktop computers, demonstrating stability and efficiency even with very large datasets.

Write-Ahead Log (WAL) Modes

ZoneTree offers four WAL modes to provide flexibility between performance and durability:

  1. Sync Mode:

    • Durability: Maximum.
    • Performance: Slower write speed.
    • Use Case: Ensures data is not lost in case of crashes or power cuts.
  2. Sync-Compressed Mode:

    • Durability: High, but slightly less than sync mode.
    • Performance: Faster write speed due to compression.
    • Use Case: Balances durability and performance; periodic jobs can persist decompressed tail records for added safety.
  3. Async-Compressed Mode:

    • Durability: Moderate.
    • Performance: Very fast write speed; logs are written in a separate thread.
    • Use Case: Suitable where immediate durability is less critical but performance is paramount.
  4. None Mode:

    • Durability: No immediate durability; relies on manual or automatic disk saves.
    • Performance: Maximum possible.
    • Use Case: Ideal for scenarios where performance is critical and data can be reconstructed or is not mission-critical.

Benchmark Environment

BenchmarkDotNet=v0.13.1, OS=Windows 10.0.22000
Processor: Intel Core i7-6850K CPU @ 3.60GHz (Skylake), 12 logical cores, 6 physical cores
Memory: 64 GB DDR4
Storage: Samsung SSD 850 EVO 1TB
Configuration: 1M mutable segment size, 2M readonly segments merge-threshold

Getting Started

ZoneTree is designed for ease of use, allowing developers to integrate and utilize its capabilities with minimal setup.

Basic Usage

using Tenray.ZoneTree;

using var zoneTree = new ZoneTreeFactory<int, string>()
    .OpenOrCreate();

zoneTree.Upsert(39, "Hello ZoneTree");

Creating a Database

using Tenray.ZoneTree;
using Tenray.ZoneTree.Comparers;
using Tenray.ZoneTree.Serializers;

var dataPath = "data/mydatabase";

using var zoneTree = new ZoneTreeFactory<int, string>()
    .SetComparer(new Int32ComparerAscending())
    .SetDataDirectory(dataPath)
    .SetKeySerializer(new Int32Serializer())
    .SetValueSerializer(new Utf8StringSerializer())
    .OpenOrCreate();

// Atomic (thread-safe) operation on single mutable-segment.
zoneTree.Upsert(39, "Hello ZoneTree!");

// Atomic operation across all segments.
zoneTree.TryAtomicAddOrUpdate(39, "a", (ref string x) =>
{
    x += "b";
    return true;
}, out var opIndex);

Maintaining the LSM Tree

Large-scale LSM Trees require periodic maintenance to ensure optimal performance and resource utilization. ZoneTree provides the IZoneTreeMaintenance interface to facilitate comprehensive maintenance tasks.

Example Usage:

using Tenray.ZoneTree;
using Tenray.ZoneTree.Maintenance;

var dataPath = "data/mydatabase";

using var zoneTree = new ZoneTreeFactory<int, string>()
    .SetComparer(new Int32ComparerAscending())
    .SetDataDirectory(dataPath)
    .SetKeySerializer(new Int32Serializer())
    .SetValueSerializer(new Utf8StringSerializer())
    .OpenOrCreate();

using var maintainer = zoneTree.CreateMaintainer();
maintainer.EnableJobForCleaningInactiveCaches = true;

// Perform read/write operations.
zoneTree.Upsert(39, "Hello ZoneTree!");

// Wait for background maintenance tasks to complete.
maintainer.WaitForBackgroundThreads();

Note: For smaller datasets, maintenance tasks may not be necessary. The default maintainer allows developers to focus on core business logic without delving into LSM tree intricacies.


Handling Deletions

In Log-Structured Merge (LSM) trees, deletions are managed by upserting a key/value pair with a deletion marker. Actual data removal occurs during the compaction stage.

By default, ZoneTree assumes that default values indicate deletion. This behavior can be customized by defining specific deletion flags or disabling deletions entirely using the DisableDeletion method.

Using an Integer Deletion Flag

In this example, -1 is used as the deletion marker for integer values:

using Tenray.ZoneTree;

using var zoneTree = new ZoneTreeFactory<int, int>()
    .SetIsDeletedDelegate((in int key, in int value) => value == -1)
    .SetMarkValueDeletedDelegate((ref int x) => x = -1)
    .OpenOrCreate();

// Deleting a key by setting its value to -1
zoneTree.Upsert(42, -1);

Using a Custom Struct for Deletion

For more control, define a custom structure to represent values and their deletion status:

using System.Runtime.InteropServices;
using Tenray.ZoneTree;

[StructLayout(LayoutKind.Sequential)]
struct MyDeletableValueType
{
    public int Number;
    public bool IsDeleted;
}

using var zoneTree = new ZoneTreeFactory<int, MyDeletableValueType>()
    .SetIsDeletedDelegate((in int key, in MyDeletableValueType value) => value.IsDeleted)
    .SetMarkValueDeletedDelegate((ref MyDeletableValueType value) => value.IsDeleted = true)
    .OpenOrCreate();

// Deleting a key by setting the IsDeleted flag
zoneTree.Upsert(42, new MyDeletableValueType { Number = 0, IsDeleted = true });

Data Iteration

ZoneTree provides efficient mechanisms to iterate over data both forward and backward, with equal performance in both directions. Iterators also support seek operations for quick access to specific keys.

Forward and Backward Iteration

using Tenray.ZoneTree;
using Tenray.ZoneTree.Collections;

using var zoneTree = new ZoneTreeFactory<int, int>()
    .OpenOrCreate();

// Forward iteration
using var iterator = zoneTree.CreateIterator();
while (iterator.Next())
{
    var key = iterator.CurrentKey;
    var value = iterator.CurrentValue;
    // Process key and value
}

// Backward iteration
using var reverseIterator = zoneTree.CreateReverseIterator();
while (reverseIterator.Next())
{
    var key = reverseIterator.CurrentKey;
    var value = reverseIterator.CurrentValue;
    // Process key and value
}

Seekable Iterator

The ZoneTreeIterator supports the Seek() method to jump to any record with O(log(n)) complexity, useful for prefix searches and range queries.

using Tenray.ZoneTree;
using Tenray.ZoneTree.Collections;

using var zoneTree = new ZoneTreeFactory<string, int>()
    .OpenOrCreate();

using var iterator = zoneTree.CreateIterator();

// Jump to the first record starting with "SomePrefix"
if (iterator.Seek("SomePrefix"))
{
    do
    {
        var key = iterator.CurrentKey;
        var value = iterator.CurrentValue;
        // Process key and value
    }
    while (iterator.Next());
}

Transaction Support

ZoneTree supports Optimistic Transactions, ensuring ACID compliance while offering flexibility through various transaction models:

  1. Fluent Transactions: Provides an intuitive, chainable API with built-in retry capabilities.
  2. Classical Transactions: Traditional approach with explicit control over transaction lifecycle.
  3. Exceptionless Transactions: Allows transaction management without relying on exceptions for control flow.

Fluent Transactions

using System.Threading.Tasks;
using Tenray.ZoneTree;
using Tenray.ZoneTree.Transaction;

using var zoneTree = new ZoneTreeFactory<int, int>()
    .OpenOrCreateTransactional();

using var transaction = zoneTree
    .BeginFluentTransaction()
    .Do(tx => zoneTree.UpsertNoThrow(tx, 3, 9))
    .Do(tx =>
    {
        if (zoneTree.TryGetNoThrow(tx, 3, out var value).IsAborted)
            return TransactionResult.Aborted();

        if (zoneTree.UpsertNoThrow(tx, 3, 21).IsAborted)
            return TransactionResult.Aborted();

        return TransactionResult.Success();
    })
    .SetRetryCountForPendingTransactions(100)
    .SetRetryCountForAbortedTransactions(10);

await transaction.CommitAsync();

Classical Transactions

using System;
using System.Threading;
using Tenray.ZoneTree;
using Tenray.ZoneTree.Transaction;

using var zoneTree = new ZoneTreeFactory<int, int>()
    .OpenOrCreateTransactional();

try
{
    var txId = zoneTree.BeginTransaction();

    zoneTree.TryGet(txId, 3, out var value);
    zoneTree.Upsert(txId, 3, 9);

    var result = zoneTree.Prepare(txId);
    while (result.IsPendingTransactions)
    {
        Thread.Sleep(100);
        result = zoneTree.Prepare(txId);
    }

    zoneTree.Commit(txId);
}
catch (TransactionAbortedException)
{
    // Handle aborted transaction (retry or cancel)
}

Exceptionless Transactions

using System;
using System.Threading.Tasks;
using Tenray.ZoneTree.Transactional;

public async Task<bool> ExecuteTransactionWithRetryAsync(ZoneTreeFactory<int, int> zoneTreeFactory, int maxRetries = 3)
{
    using var zoneTree = zoneTreeFactory.OpenOrCreateTransactional();
    var transactionId = zoneTree.BeginTransaction();

    // Execute the operations within the transaction
    var result = zoneTree.UpsertNoThrow(transactionId, 1, 100);
    if (result.IsAborted)
        return false; // Abort the transaction and return false on failure.

    result = zoneTree.UpsertNoThrow(transactionId, 2, 200);
    if (result.IsAborted)
        return false; // Abort the transaction and return false on failure.

    // Retry only the prepare step
    int retryCount = 0;
    while (retryCount <= maxRetries)
    {
        var prepareResult = zoneTree.PrepareNoThrow(transactionId);
        if (prepareResult.IsAborted)
            return false; // Abort the transaction and return false on failure.

        if (prepareResult.IsPendingTransactions)
        {
            await Task.Delay(100); // Simple delay before retrying
            retryCount++;
            continue; // Retry the prepare step
        }

        if (prepareResult.IsReadyToCommit)
            break; // Exit loop if ready to commit
    }

    // After successfully preparing, commit the transaction
    var commitResult = zoneTree.CommitNoThrow(transactionId);
    if (commitResult.IsAborted)
        return false; // Abort the transaction and return false on failure.

    // Transaction committed successfully
    return true;
}

Feature Highlights

Feature Description
.NET Compatibility Works seamlessly with .NET primitives, structs, and classes.
High Performance and Low Memory Consumption Optimized algorithms ensure fast operations with minimal resource usage.
Crash Resilience Robust mechanisms protect data integrity against unexpected failures.
Efficient Disk Space Utilization Optimized storage strategies minimize disk space requirements.
Data Compression Supports WAL and DiskSegment data compression for efficient storage.
Fast Load/Unload Quickly load and unload large datasets as needed.
Standard CRUD Operations Provides intuitive and straightforward Create, Read, Update, Delete functionalities.
Optimistic Transactions Supports concurrent operations with minimal locking overhead.
Atomic Read-Modify-Update Ensures data consistency during complex update operations.
In-Memory and Disk Storage Flexibly operate entirely in memory or persist data to various storage backends.
Cloud Storage Support Compatible with cloud-based storage solutions for scalable deployments.
ACID Compliance Guarantees Atomicity, Consistency, Isolation, and Durability across transactions.
Multiple WAL Modes Choose from four different WAL modes to balance performance and durability.
Configurable Memory Usage Adjust the amount of data retained in memory based on application needs.
Partial and Complete Data Loading Load data partially (with sparse arrays) or completely to and from disk.
Bidirectional Iteration Efficiently iterate over data both forward and backward.
Optional Dirty Reads Allow for faster reads when strict consistency is not required.
Embeddable Design Integrate ZoneTree directly into applications without external dependencies.
SSD Optimization Tailored for optimal performance on solid-state drives.
Exceptionless Transaction API Manage transactions smoothly without relying on exceptions for control flow.
Fluent Transaction API Utilize an intuitive, chainable transaction interface with retry capabilities.
Easy Maintenance Simplified maintenance processes ensure consistent performance.
Configurable LSM Merger Customize merge operations to suit specific workload patterns.
Transparent Implementation Clear and straightforward codebase reveals internal workings for easy understanding.
Open-Source with MIT License Freely use, modify, and distribute under a permissive license.
Transaction Log Compaction Efficiently manage and reduce the size of transaction logs.
Transaction Analysis and Control Analyze and manage transactions for improved performance and reliability.
Efficient Concurrency Control Minimal overhead through innovative separation of concurrency stamps and data.
Time-To-Live (TTL) Support Automatically expire data after a specified duration.
Custom Serializer and Comparer Support Implement custom logic for data serialization and comparison.
Multiple Disk Segments Mode Divide data files into configurable chunks for better manageability and performance.
Snapshot Iterators Create consistent snapshots for data analysis and backup purposes.

ZoneTree.FullTextSearch

ZoneTree.FullTextSearch is an extension library built upon ZoneTree, providing a high-performance and flexible full-text search engine for .NET applications.

Key Features Include:

  • Fast and Efficient Indexing: Handles large volumes of text data with impressive speed.
  • Advanced Query Support: Enables complex search queries with support for Boolean operators and faceted search.
  • Customizable Components: Allows integration of custom tokenizers, stemmers, and normalizers to suit specific application needs.
  • Scalable Architecture: Designed to scale seamlessly with growing data and usage demands.

For more information and detailed documentation, visit the ZoneTree.FullTextSearch GitHub Repository.


Documentation

Explore comprehensive guides and API references to get the most out of ZoneTree:


Contributing

Contributions are highly appreciated and welcomed! Here’s how you can help:

  1. Write Tests and Benchmarks: Improve code reliability and performance analysis.
  2. Enhance Documentation: Help others understand and utilize ZoneTree effectively.
  3. Submit Feature Requests and Bug Reports: Share ideas and report issues to refine ZoneTree further.
  4. Optimize Performance: Contribute optimizations and improvements to existing functionalities.

Please follow the guidelines outlined in CONTRIBUTING.md to get started.


License

ZoneTree is licensed under the MIT License, allowing for flexible use and distribution.

Product Compatible and additional computed target framework versions.
.NET net6.0 is compatible.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 is compatible.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 is compatible. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (5)

Showing the top 5 NuGet packages that depend on ZoneTree:

Package Downloads
DifferentialComputeDotNet.Core

Package Description

ZoneTree.FullTextSearch

ZoneTree.FullTextSearch is an open-source library that extends ZoneTree to provide efficient full-text search capabilities. It offers a fast, embedded search engine suitable for applications that require high performance and do not rely on external databases.

ManagedCode.ZoneTree.BlobFileSystem

Azure Blob FileSystem for ZoneTree

ManagedCode.Database.ZoneTree

Repository for ZoneTree

RickDotNet.FusionStore.Stores.ZoneTree

A FusionCache and ZoneTree inspired data store abstraction.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last updated
1.8.4 344 11/14/2024
1.8.3 232 10/16/2024
1.8.2 326 9/7/2024
1.8.1 128 9/7/2024
1.8.0 135 9/1/2024
1.7.9 147 8/30/2024
1.7.8 112 8/30/2024
1.7.7 175 8/24/2024
1.7.6 175 8/17/2024
1.7.5 141 8/17/2024
1.7.4 138 8/11/2024
1.7.3 119 8/10/2024
1.7.2 131 7/19/2024
1.7.1 265 6/14/2024
1.7.0 2,681 12/12/2023
1.6.9 649 9/13/2023
1.6.8 141 9/13/2023
1.6.7 139 9/13/2023
1.6.6 190 8/18/2023
1.6.5 201 6/17/2023
1.6.4 145 6/16/2023
1.6.3 214 5/29/2023
1.6.2 16,897 5/26/2023
1.6.1 292 4/5/2023
1.6.0 1,907 1/14/2023
1.5.9 313 1/14/2023
1.5.8 1,011 11/20/2022
1.5.7 387 11/14/2022
1.5.6 359 11/13/2022
1.5.5 472 10/20/2022
1.5.2 501 9/14/2022
1.5.1 420 9/3/2022
1.5.0 421 9/2/2022
1.4.9 423 8/31/2022
1.4.8 386 8/30/2022
1.4.7 422 8/30/2022
1.4.6 431 8/29/2022
1.4.5 445 8/28/2022
1.4.4 613 8/27/2022
1.4.3 431 8/26/2022
1.4.2 424 8/26/2022
1.4.1 393 8/26/2022
1.4.0 423 8/25/2022
1.3.9 409 8/25/2022
1.3.8 427 8/24/2022
1.3.7 693 8/23/2022
1.3.6 408 8/22/2022
1.3.5 430 8/22/2022
1.3.4 423 8/21/2022
1.3.3 410 8/18/2022
1.3.2 444 8/17/2022
1.3.1 408 8/17/2022
1.3.0 421 8/17/2022
1.2.9 409 8/16/2022
1.2.8 402 8/15/2022
1.2.7 430 8/15/2022
1.2.6 418 8/13/2022
1.2.5 433 8/13/2022
1.2.4 418 8/13/2022
1.2.3 443 8/9/2022
1.2.2 398 8/9/2022
1.2.1 441 8/9/2022
1.2.0 460 8/8/2022
1.1.9 434 8/8/2022
1.1.8 424 8/8/2022
1.1.7 448 8/8/2022
1.1.6 413 8/7/2022
1.1.5 437 8/6/2022
1.1.4 421 8/6/2022
1.1.3 428 8/5/2022
1.1.2 440 8/5/2022
1.1.1 436 7/27/2022
1.1.0 440 7/27/2022
1.0.9 429 7/25/2022
1.0.8 415 7/24/2022
1.0.7 390 7/23/2022
1.0.6 428 7/20/2022
1.0.5 442 7/18/2022
1.0.4 449 7/11/2022
1.0.3 481 7/11/2022
1.0.2 470 7/11/2022
1.0.1 455 7/6/2022
1.0.0 454 7/6/2022