gorocksdb: github.com/tecbot/gorocksdb Index | Files

package gorocksdb

import "github.com/tecbot/gorocksdb"

Package gorocksdb provides the ability to create and access RocksDB databases.

gorocksdb.OpenDb opens and creates databases.

bbto := gorocksdb.NewDefaultBlockBasedTableOptions()
bbto.SetBlockCache(gorocksdb.NewLRUCache(3 << 30))
opts := gorocksdb.NewDefaultOptions()
opts.SetBlockBasedTableFactory(bbto)
opts.SetCreateIfMissing(true)
db, err := gorocksdb.OpenDb(opts, "/path/to/db")

The DB struct returned by OpenDb provides DB.Get, DB.Put, DB.Merge and DB.Delete to modify and query the database.

ro := gorocksdb.NewDefaultReadOptions()
wo := gorocksdb.NewDefaultWriteOptions()
// if ro and wo are not used again, be sure to Close them.
err = db.Put(wo, []byte("foo"), []byte("bar"))
...
value, err := db.Get(ro, []byte("foo"))
defer value.Free()
...
err = db.Delete(wo, []byte("foo"))

For bulk reads, use an Iterator. If you want to avoid disturbing your live traffic while doing the bulk read, be sure to call SetFillCache(false) on the ReadOptions you use when creating the Iterator.

ro := gorocksdb.NewDefaultReadOptions()
ro.SetFillCache(false)
it := db.NewIterator(ro)
defer it.Close()
it.Seek([]byte("foo"))
for it = it; it.Valid(); it.Next() {
	key := it.Key()
	value := it.Value()
	fmt.Printf("Key: %v Value: %v\n", key.Data(), value.Data())
	key.Free()
	value.Free()
}
if err := it.Err(); err != nil {
	...
}

Batched, atomic writes can be performed with a WriteBatch and DB.Write.

wb := gorocksdb.NewWriteBatch()
// defer wb.Close or use wb.Clear and reuse.
wb.Delete([]byte("foo"))
wb.Put([]byte("foo"), []byte("bar"))
wb.Put([]byte("bar"), []byte("foo"))
err := db.Write(wo, wb)

If your working dataset does not fit in memory, you'll want to add a bloom filter to your database. NewBloomFilter and BlockBasedTableOptions.SetFilterPolicy is what you want. NewBloomFilter is amount of bits in the filter to use per key in your database.

filter := gorocksdb.NewBloomFilter(10)
bbto := gorocksdb.NewDefaultBlockBasedTableOptions()
bbto.SetFilterPolicy(filter)
opts.SetBlockBasedTableFactory(bbto)
db, err := gorocksdb.OpenDb(opts, "/path/to/db")

If you're using a custom comparator in your code, be aware you may have to make your own filter policy object.

This documentation is not a complete discussion of RocksDB. Please read the RocksDB documentation <http://rocksdb.org/> for information on its operation. You'll find lots of goodies there.

Index

Package Files

array.go backup.go cache.go cf_handle.go checkpoint.go compaction_filter.go comparator.go cow.go db.go dbpath.go doc.go dynflag.go env.go filter_policy.go iterator.go memory_usage.go merge_operator.go options.go options_block_based_table.go options_compaction.go options_compression.go options_env.go options_flush.go options_ingest.go options_read.go options_transaction.go options_transactiondb.go options_write.go ratelimiter.go slice.go slice_transform.go snapshot.go sst_file_writer.go transaction.go transactiondb.go util.go wal_iterator.go write_batch.go

Constants

const (
    NoCompression     = CompressionType(C.rocksdb_no_compression)
    SnappyCompression = CompressionType(C.rocksdb_snappy_compression)
    ZLibCompression   = CompressionType(C.rocksdb_zlib_compression)
    Bz2Compression    = CompressionType(C.rocksdb_bz2_compression)
    LZ4Compression    = CompressionType(C.rocksdb_lz4_compression)
    LZ4HCCompression  = CompressionType(C.rocksdb_lz4hc_compression)
    XpressCompression = CompressionType(C.rocksdb_xpress_compression)
    ZSTDCompression   = CompressionType(C.rocksdb_zstd_compression)
)

Compression types.

const (
    LevelCompactionStyle     = CompactionStyle(C.rocksdb_level_compaction)
    UniversalCompactionStyle = CompactionStyle(C.rocksdb_universal_compaction)
    FIFOCompactionStyle      = CompactionStyle(C.rocksdb_fifo_compaction)
)

Compaction styles.

const (
    NoneCompactionAccessPattern       = CompactionAccessPattern(0)
    NormalCompactionAccessPattern     = CompactionAccessPattern(1)
    SequentialCompactionAccessPattern = CompactionAccessPattern(2)
    WillneedCompactionAccessPattern   = CompactionAccessPattern(3)
)

Access patterns for compaction.

const (
    DebugInfoLogLevel = InfoLogLevel(0)
    InfoInfoLogLevel  = InfoLogLevel(1)
    WarnInfoLogLevel  = InfoLogLevel(2)
    ErrorInfoLogLevel = InfoLogLevel(3)
    FatalInfoLogLevel = InfoLogLevel(4)
)

Log leves.

const (
    TolerateCorruptedTailRecordsRecovery = WALRecoveryMode(0)
    AbsoluteConsistencyRecovery          = WALRecoveryMode(1)
    PointInTimeRecovery                  = WALRecoveryMode(2)
    SkipAnyCorruptedRecordsRecovery      = WALRecoveryMode(3)
)
const (
    // A space efficient index block that is optimized for
    // binary-search-based index.
    KBinarySearchIndexType = 0
    // The hash index, if enabled, will do the hash lookup when
    // `Options.prefix_extractor` is provided.
    KHashSearchIndexType = 1
    // A two-level index implementation. Both levels are binary search indexes.
    KTwoLevelIndexSearchIndexType = 2
)
const (
    CompactionStopStyleSimilarSize = UniversalCompactionStopStyle(C.rocksdb_similar_size_compaction_stop_style)
    CompactionStopStyleTotalSize   = UniversalCompactionStopStyle(C.rocksdb_total_size_compaction_stop_style)
)

Compaction stop style types.

const (
    // ReadAllTier reads data in memtable, block cache, OS cache or storage.
    ReadAllTier = ReadTier(0)
    // BlockCacheTier reads data in memtable or block cache.
    BlockCacheTier = ReadTier(1)
)

func DestroyDBPaths Uses

func DestroyDBPaths(dbpaths []*DBPath)

DestroyDBPaths deallocates all DBPath objects in dbpaths.

func DestroyDb Uses

func DestroyDb(name string, opts *Options) error

DestroyDb removes a database entirely, removing everything from the filesystem.

func ListColumnFamilies Uses

func ListColumnFamilies(opts *Options, name string) ([]string, error)

ListColumnFamilies lists the names of the column families in the DB.

func OpenDbColumnFamilies Uses

func OpenDbColumnFamilies(
    opts *Options,
    name string,
    cfNames []string,
    cfOpts []*Options,
) (*DB, []*ColumnFamilyHandle, error)

OpenDbColumnFamilies opens a database with the specified column families.

func OpenDbForReadOnlyColumnFamilies Uses

func OpenDbForReadOnlyColumnFamilies(
    opts *Options,
    name string,
    cfNames []string,
    cfOpts []*Options,
    errorIfLogFileExist bool,
) (*DB, []*ColumnFamilyHandle, error)

OpenDbForReadOnlyColumnFamilies opens a database with the specified column families in read only mode.

func RepairDb Uses

func RepairDb(name string, opts *Options) error

RepairDb repairs a database.

type BackupEngine Uses

type BackupEngine struct {
    // contains filtered or unexported fields
}

BackupEngine is a reusable handle to a RocksDB Backup, created by OpenBackupEngine.

func OpenBackupEngine Uses

func OpenBackupEngine(opts *Options, path string) (*BackupEngine, error)

OpenBackupEngine opens a backup engine with specified options.

func (*BackupEngine) Close Uses

func (b *BackupEngine) Close()

Close close the backup engine and cleans up state The backups already taken remain on storage.

func (*BackupEngine) CreateNewBackup Uses

func (b *BackupEngine) CreateNewBackup(db *DB) error

CreateNewBackup takes a new backup from db.

func (*BackupEngine) CreateNewBackupFlush Uses

func (b *BackupEngine) CreateNewBackupFlush(db *DB, flush bool) error

CreateNewBackupFlush takes a new backup from db. If flush is set to true, it flushes the WAL before taking the backup.

func (*BackupEngine) GetInfo Uses

func (b *BackupEngine) GetInfo() *BackupEngineInfo

GetInfo gets an object that gives information about the backups that have already been taken

func (*BackupEngine) PurgeOldBackups Uses

func (b *BackupEngine) PurgeOldBackups(n uint32) error

PurgeOldBackups deletes all backups older than the latest 'n' backups

func (*BackupEngine) RestoreDBFromLatestBackup Uses

func (b *BackupEngine) RestoreDBFromLatestBackup(dbDir, walDir string, ro *RestoreOptions) error

RestoreDBFromLatestBackup restores the latest backup to dbDir. walDir is where the write ahead logs are restored to and usually the same as dbDir.

func (*BackupEngine) UnsafeGetBackupEngine Uses

func (b *BackupEngine) UnsafeGetBackupEngine() unsafe.Pointer

UnsafeGetBackupEngine returns the underlying c backup engine.

type BackupEngineInfo Uses

type BackupEngineInfo struct {
    // contains filtered or unexported fields
}

BackupEngineInfo represents the information about the backups in a backup engine instance. Use this to get the state of the backup like number of backups and their ids and timestamps etc.

func (*BackupEngineInfo) Destroy Uses

func (b *BackupEngineInfo) Destroy()

Destroy destroys the backup engine info instance.

func (*BackupEngineInfo) GetBackupId Uses

func (b *BackupEngineInfo) GetBackupId(index int) int64

GetBackupId gets an id that uniquely identifies a backup regardless of its position.

func (*BackupEngineInfo) GetCount Uses

func (b *BackupEngineInfo) GetCount() int

GetCount gets the number backsup available.

func (*BackupEngineInfo) GetNumFiles Uses

func (b *BackupEngineInfo) GetNumFiles(index int) int32

GetNumFiles gets the number of files in the backup index.

func (*BackupEngineInfo) GetSize Uses

func (b *BackupEngineInfo) GetSize(index int) int64

GetSize get the size of the backup in bytes.

func (*BackupEngineInfo) GetTimestamp Uses

func (b *BackupEngineInfo) GetTimestamp(index int) int64

GetTimestamp gets the timestamp at which the backup index was taken.

type BlockBasedTableOptions Uses

type BlockBasedTableOptions struct {
    // contains filtered or unexported fields
}

BlockBasedTableOptions represents block-based table options.

func NewDefaultBlockBasedTableOptions Uses

func NewDefaultBlockBasedTableOptions() *BlockBasedTableOptions

NewDefaultBlockBasedTableOptions creates a default BlockBasedTableOptions object.

func NewNativeBlockBasedTableOptions Uses

func NewNativeBlockBasedTableOptions(c *C.rocksdb_block_based_table_options_t) *BlockBasedTableOptions

NewNativeBlockBasedTableOptions creates a BlockBasedTableOptions object.

func (*BlockBasedTableOptions) Destroy Uses

func (opts *BlockBasedTableOptions) Destroy()

Destroy deallocates the BlockBasedTableOptions object.

func (*BlockBasedTableOptions) SetBlockCache Uses

func (opts *BlockBasedTableOptions) SetBlockCache(cache *Cache)

SetBlockCache sets the control over blocks (user data is stored in a set of blocks, and a block is the unit of reading from disk).

If set, use the specified cache for blocks. If nil, rocksdb will auoptsmatically create and use an 8MB internal cache. Default: nil

func (*BlockBasedTableOptions) SetBlockCacheCompressed Uses

func (opts *BlockBasedTableOptions) SetBlockCacheCompressed(cache *Cache)

SetBlockCacheCompressed sets the cache for compressed blocks. If nil, rocksdb will not use a compressed block cache. Default: nil

func (*BlockBasedTableOptions) SetBlockRestartInterval Uses

func (opts *BlockBasedTableOptions) SetBlockRestartInterval(blockRestartInterval int)

SetBlockRestartInterval sets the number of keys between restart points for delta encoding of keys. This parameter can be changed dynamically. Most clients should leave this parameter alone. Default: 16

func (*BlockBasedTableOptions) SetBlockSize Uses

func (opts *BlockBasedTableOptions) SetBlockSize(blockSize int)

SetBlockSize sets the approximate size of user data packed per block. Note that the block size specified here corresponds opts uncompressed data. The actual size of the unit read from disk may be smaller if compression is enabled. This parameter can be changed dynamically. Default: 4K

func (*BlockBasedTableOptions) SetBlockSizeDeviation Uses

func (opts *BlockBasedTableOptions) SetBlockSizeDeviation(blockSizeDeviation int)

SetBlockSizeDeviation sets the block size deviation. This is used opts close a block before it reaches the configured 'block_size'. If the percentage of free space in the current block is less than this specified number and adding a new record opts the block will exceed the configured block size, then this block will be closed and the new record will be written opts the next block. Default: 10

func (*BlockBasedTableOptions) SetCacheIndexAndFilterBlocks Uses

func (opts *BlockBasedTableOptions) SetCacheIndexAndFilterBlocks(value bool)

SetCacheIndexAndFilterBlocks is indicating if we'd put index/filter blocks to the block cache. If not specified, each "table reader" object will pre-load index/filter block during table initialization. Default: false

func (*BlockBasedTableOptions) SetCacheIndexAndFilterBlocksWithHighPriority Uses

func (opts *BlockBasedTableOptions) SetCacheIndexAndFilterBlocksWithHighPriority(value bool)

SetCacheIndexAndFilterBlocksWithHighPriority sets cache index and filter blocks with high priority (if cache_index_and_filter_blocks is enabled). If set to true, depending on implementation of block cache, index and filter blocks may be less likely to be evicted than data blocks.

func (*BlockBasedTableOptions) SetFilterPolicy Uses

func (opts *BlockBasedTableOptions) SetFilterPolicy(fp FilterPolicy)

SetFilterPolicy sets the filter policy opts reduce disk reads. Many applications will benefit from passing the result of NewBloomFilterPolicy() here. Default: nil

func (*BlockBasedTableOptions) SetFormatVersion Uses

func (opts *BlockBasedTableOptions) SetFormatVersion(version int)

SetFormatVersion sets the format version. We currently have five versions: 0 -- This version is currently written out by all RocksDB's versions by default. Can be read by really old RocksDB's. Doesn't support changing checksum (default is CRC32). 1 -- Can be read by RocksDB's versions since 3.0. Supports non-default checksum, like xxHash. It is written by RocksDB when BlockBasedTableOptions::checksum is something other than kCRC32c. (version 0 is silently upconverted) 2 -- Can be read by RocksDB's versions since 3.10. Changes the way we encode compressed blocks with LZ4, BZip2 and Zlib compression. If you don't plan to run RocksDB before version 3.10, you should probably use this. 3 -- Can be read by RocksDB's versions since 5.15. Changes the way we encode the keys in index blocks. If you don't plan to run RocksDB before version 5.15, you should probably use this. This option only affects newly written tables. When reading existing tables, the information about version is read from the footer. 4 -- Can be read by RocksDB's versions since 5.16. Changes the way we encode the values in index blocks. If you don't plan to run RocksDB before version 5.16 and you are using index_block_restart_interval > 1, you should probably use this as it would reduce the index size. This option only affects newly written tables. When reading existing tables, the information about version is read from the footer. Default: 2

func (*BlockBasedTableOptions) SetIndexBlockRestartInterval Uses

func (opts *BlockBasedTableOptions) SetIndexBlockRestartInterval(indexBlockRestartInterval int)

SetIndexBlockRestartInterval is the same as SetBlockRestartInterval but used for the index block. Default: 1

func (*BlockBasedTableOptions) SetIndexType Uses

func (opts *BlockBasedTableOptions) SetIndexType(value IndexType)

SetIndexType sets the index type used for this table. kBinarySearch: A space efficient index block that is optimized for binary-search-based index.

kHashSearch: The hash index, if enabled, will do the hash lookup when `Options.prefix_extractor` is provided.

kTwoLevelIndexSearch: A two-level index implementation. Both levels are binary search indexes. Default: kBinarySearch

func (*BlockBasedTableOptions) SetMetadataBlockSize Uses

func (opts *BlockBasedTableOptions) SetMetadataBlockSize(metadataBlockSize uint64)

SetMetadataBlockSize sets the block size for partitioned metadata. Currently applied to indexes when kTwoLevelIndexSearch is used and to filters when partition_filters is used. Note: Since in the current implementation the filters and index partitions are aligned, an index/filter block is created when either index or filter block size reaches the specified limit. Note: this limit is currently applied to only index blocks; a filter partition is cut right after an index block is cut Default: 4096

func (*BlockBasedTableOptions) SetNoBlockCache Uses

func (opts *BlockBasedTableOptions) SetNoBlockCache(value bool)

SetNoBlockCache specify whether block cache should be used or not. Default: false

func (*BlockBasedTableOptions) SetPartitionFilters Uses

func (opts *BlockBasedTableOptions) SetPartitionFilters(value bool)

SetPartitionFilters sets using partitioned full filters for each SST file. This option is incompatible with block-based filters. Note: currently this option requires kTwoLevelIndexSearch to be set as well. Default: false

func (*BlockBasedTableOptions) SetPinL0FilterAndIndexBlocksInCache Uses

func (opts *BlockBasedTableOptions) SetPinL0FilterAndIndexBlocksInCache(value bool)

SetPinL0FilterAndIndexBlocksInCache sets cache_index_and_filter_blocks. If is true and the below is true (hash_index_allow_collision), then filter and index blocks are stored in the cache, but a reference is held in the "table reader" object so the blocks are pinned and only evicted from cache when the table reader is freed.

func (*BlockBasedTableOptions) SetPinTopLevelIndexAndFilter Uses

func (opts *BlockBasedTableOptions) SetPinTopLevelIndexAndFilter(value bool)

SetPinTopLevelIndexAndFilter set that if cache_index_and_filter_blocks is true, then the top-level index of partitioned filter and index blocks are stored in the cache, but a reference is held in the "table reader" object so the blocks are pinned and only evicted from cache when the table reader is freed. This is not limited to l0 in LSM tree.

func (*BlockBasedTableOptions) SetUseDeltaEncoding Uses

func (opts *BlockBasedTableOptions) SetUseDeltaEncoding(value bool)

SetUseDeltaEncoding sets using delta encoding to compress keys in blocks. ReadOptions::pin_data requires this option to be disabled.

func (*BlockBasedTableOptions) SetWholeKeyFiltering Uses

func (opts *BlockBasedTableOptions) SetWholeKeyFiltering(value bool)

SetWholeKeyFiltering specify if whole keys in the filter (not just prefixes) should be placed. This must generally be true for gets opts be efficient. Default: true

type COWList Uses

type COWList struct {
    // contains filtered or unexported fields
}

COWList implements a copy-on-write list. It is intended to be used by go callback registry for CGO, which is read-heavy with occasional writes. Reads do not block; Writes do not block reads (or vice versa), but only one write can occur at once;

func NewCOWList Uses

func NewCOWList() *COWList

NewCOWList creates a new COWList.

func (*COWList) Append Uses

func (c *COWList) Append(i interface{}) int

Append appends an item to the COWList and returns the index for that item.

func (*COWList) Get Uses

func (c *COWList) Get(index int) interface{}

Get gets the item at index.

type Cache Uses

type Cache struct {
    // contains filtered or unexported fields
}

Cache is a cache used to store data read from data in memory.

func NewLRUCache Uses

func NewLRUCache(capacity uint64) *Cache

NewLRUCache creates a new LRU Cache object with the capacity given.

func NewNativeCache Uses

func NewNativeCache(c *C.rocksdb_cache_t) *Cache

NewNativeCache creates a Cache object.

func (*Cache) Destroy Uses

func (c *Cache) Destroy()

Destroy deallocates the Cache object.

func (*Cache) GetPinnedUsage Uses

func (c *Cache) GetPinnedUsage() uint64

GetPinnedUsage returns the Cache pinned memory usage.

func (*Cache) GetUsage Uses

func (c *Cache) GetUsage() uint64

GetUsage returns the Cache memory usage.

type Checkpoint Uses

type Checkpoint struct {
    // contains filtered or unexported fields
}

Checkpoint provides Checkpoint functionality. Checkpoints provide persistent snapshots of RocksDB databases.

func NewNativeCheckpoint Uses

func NewNativeCheckpoint(c *C.rocksdb_checkpoint_t) *Checkpoint

NewNativeCheckpoint creates a new checkpoint.

func (*Checkpoint) CreateCheckpoint Uses

func (checkpoint *Checkpoint) CreateCheckpoint(checkpoint_dir string, log_size_for_flush uint64) error

CreateCheckpoint builds an openable snapshot of RocksDB on the same disk, which accepts an output directory on the same disk, and under the directory (1) hard-linked SST files pointing to existing live SST files SST files will be copied if output directory is on a different filesystem (2) a copied manifest files and other files The directory should not already exist and will be created by this API. The directory will be an absolute path log_size_for_flush: if the total log file size is equal or larger than this value, then a flush is triggered for all the column families. The default value is 0, which means flush is always triggered. If you move away from the default, the checkpoint may not contain up-to-date data if WAL writing is not always enabled. Flush will always trigger if it is 2PC.

func (*Checkpoint) Destroy Uses

func (checkpoint *Checkpoint) Destroy()

Destroy deallocates the Checkpoint object.

type ColumnFamilyHandle Uses

type ColumnFamilyHandle struct {
    // contains filtered or unexported fields
}

ColumnFamilyHandle represents a handle to a ColumnFamily.

func NewNativeColumnFamilyHandle Uses

func NewNativeColumnFamilyHandle(c *C.rocksdb_column_family_handle_t) *ColumnFamilyHandle

NewNativeColumnFamilyHandle creates a ColumnFamilyHandle object.

func (*ColumnFamilyHandle) Destroy Uses

func (h *ColumnFamilyHandle) Destroy()

Destroy calls the destructor of the underlying column family handle.

func (*ColumnFamilyHandle) UnsafeGetCFHandler Uses

func (h *ColumnFamilyHandle) UnsafeGetCFHandler() unsafe.Pointer

UnsafeGetCFHandler returns the underlying c column family handle.

type ColumnFamilyHandles Uses

type ColumnFamilyHandles []*ColumnFamilyHandle

type CompactionAccessPattern Uses

type CompactionAccessPattern uint

CompactionAccessPattern specifies the access patern in compaction.

type CompactionFilter Uses

type CompactionFilter interface {
    // If the Filter function returns false, it indicates
    // that the kv should be preserved, while a return value of true
    // indicates that this key-value should be removed from the
    // output of the compaction. The application can inspect
    // the existing value of the key and make decision based on it.
    //
    // When the value is to be preserved, the application has the option
    // to modify the existing value and pass it back through a new value.
    // To retain the previous value, simply return nil
    //
    // If multithreaded compaction is being used *and* a single CompactionFilter
    // instance was supplied via SetCompactionFilter, this the Filter function may be
    // called from different threads concurrently. The application must ensure
    // that the call is thread-safe.
    Filter(level int, key, val []byte) (remove bool, newVal []byte)

    // The name of the compaction filter, for logging
    Name() string
}

A CompactionFilter can be used to filter keys during compaction time.

func NewNativeCompactionFilter Uses

func NewNativeCompactionFilter(c *C.rocksdb_compactionfilter_t) CompactionFilter

NewNativeCompactionFilter creates a CompactionFilter object.

type CompactionStyle Uses

type CompactionStyle uint

CompactionStyle specifies the compaction style.

type Comparator Uses

type Comparator interface {
    // Three-way comparison. Returns value:
    //   < 0 iff "a" < "b",
    //   == 0 iff "a" == "b",
    //   > 0 iff "a" > "b"
    Compare(a, b []byte) int

    // The name of the comparator.
    Name() string
}

A Comparator object provides a total order across slices that are used as keys in an sstable or a database.

func NewNativeComparator Uses

func NewNativeComparator(c *C.rocksdb_comparator_t) Comparator

NewNativeComparator creates a Comparator object.

type CompressionOptions Uses

type CompressionOptions struct {
    WindowBits   int
    Level        int
    Strategy     int
    MaxDictBytes int
}

CompressionOptions represents options for different compression algorithms like Zlib.

func NewCompressionOptions Uses

func NewCompressionOptions(windowBits, level, strategy, maxDictBytes int) *CompressionOptions

NewCompressionOptions creates a CompressionOptions object.

func NewDefaultCompressionOptions Uses

func NewDefaultCompressionOptions() *CompressionOptions

NewDefaultCompressionOptions creates a default CompressionOptions object.

type CompressionType Uses

type CompressionType uint

CompressionType specifies the block compression. DB contents are stored in a set of blocks, each of which holds a sequence of key,value pairs. Each block may be compressed before being stored in a file. The following enum describes which compression method (if any) is used to compress a block.

type DB Uses

type DB struct {
    // contains filtered or unexported fields
}

DB is a reusable handle to a RocksDB database on disk, created by Open.

func OpenDb Uses

func OpenDb(opts *Options, name string) (*DB, error)

OpenDb opens a database with the specified options.

func OpenDbForReadOnly Uses

func OpenDbForReadOnly(opts *Options, name string, errorIfLogFileExist bool) (*DB, error)

OpenDbForReadOnly opens a database with the specified options for readonly usage.

func OpenDbWithTTL Uses

func OpenDbWithTTL(opts *Options, name string, ttl int) (*DB, error)

OpenDbWithTTL opens a database with TTL support with the specified options.

func (*DB) Close Uses

func (db *DB) Close()

Close closes the database.

func (*DB) CompactRange Uses

func (db *DB) CompactRange(r Range)

CompactRange runs a manual compaction on the Range of keys given. This is not likely to be needed for typical usage.

func (*DB) CompactRangeCF Uses

func (db *DB) CompactRangeCF(cf *ColumnFamilyHandle, r Range)

CompactRangeCF runs a manual compaction on the Range of keys given on the given column family. This is not likely to be needed for typical usage.

func (*DB) CreateColumnFamily Uses

func (db *DB) CreateColumnFamily(opts *Options, name string) (*ColumnFamilyHandle, error)

CreateColumnFamily create a new column family.

func (*DB) Delete Uses

func (db *DB) Delete(opts *WriteOptions, key []byte) error

Delete removes the data associated with the key from the database.

func (*DB) DeleteCF Uses

func (db *DB) DeleteCF(opts *WriteOptions, cf *ColumnFamilyHandle, key []byte) error

DeleteCF removes the data associated with the key from the database and column family.

func (*DB) DeleteFile Uses

func (db *DB) DeleteFile(name string)

DeleteFile deletes the file name from the db directory and update the internal state to reflect that. Supports deletion of sst and log files only. 'name' must be path relative to the db directory. eg. 000001.sst, /archive/000003.log.

func (*DB) DeleteFileInRange Uses

func (db *DB) DeleteFileInRange(r Range) error

DeleteFileInRange deletes SST files that contain keys between the Range, [r.Start, r.Limit]

func (*DB) DeleteFileInRangeCF Uses

func (db *DB) DeleteFileInRangeCF(cf *ColumnFamilyHandle, r Range) error

DeleteFileInRangeCF deletes SST files that contain keys between the Range, [r.Start, r.Limit], and belong to a given column family

func (*DB) DisableFileDeletions Uses

func (db *DB) DisableFileDeletions() error

DisableFileDeletions disables file deletions and should be used when backup the database.

func (*DB) DropColumnFamily Uses

func (db *DB) DropColumnFamily(c *ColumnFamilyHandle) error

DropColumnFamily drops a column family.

func (*DB) EnableFileDeletions Uses

func (db *DB) EnableFileDeletions(force bool) error

EnableFileDeletions enables file deletions for the database.

func (*DB) Flush Uses

func (db *DB) Flush(opts *FlushOptions) error

Flush triggers a manuel flush for the database.

func (*DB) Get Uses

func (db *DB) Get(opts *ReadOptions, key []byte) (*Slice, error)

Get returns the data associated with the key from the database.

func (*DB) GetApproximateSizes Uses

func (db *DB) GetApproximateSizes(ranges []Range) []uint64

GetApproximateSizes returns the approximate number of bytes of file system space used by one or more key ranges.

The keys counted will begin at Range.Start and end on the key before Range.Limit.

func (*DB) GetApproximateSizesCF Uses

func (db *DB) GetApproximateSizesCF(cf *ColumnFamilyHandle, ranges []Range) []uint64

GetApproximateSizesCF returns the approximate number of bytes of file system space used by one or more key ranges in the column family.

The keys counted will begin at Range.Start and end on the key before Range.Limit.

func (*DB) GetBytes Uses

func (db *DB) GetBytes(opts *ReadOptions, key []byte) ([]byte, error)

GetBytes is like Get but returns a copy of the data.

func (*DB) GetCF Uses

func (db *DB) GetCF(opts *ReadOptions, cf *ColumnFamilyHandle, key []byte) (*Slice, error)

GetCF returns the data associated with the key from the database and column family.

func (*DB) GetLatestSequenceNumber Uses

func (db *DB) GetLatestSequenceNumber() uint64

func (*DB) GetLiveFilesMetaData Uses

func (db *DB) GetLiveFilesMetaData() []LiveFileMetadata

GetLiveFilesMetaData returns a list of all table files with their level, start key and end key.

func (*DB) GetPinned Uses

func (db *DB) GetPinned(opts *ReadOptions, key []byte) (*PinnableSliceHandle, error)

GetPinned returns the data associated with the key from the database.

func (*DB) GetProperty Uses

func (db *DB) GetProperty(propName string) string

GetProperty returns the value of a database property.

func (*DB) GetPropertyCF Uses

func (db *DB) GetPropertyCF(propName string, cf *ColumnFamilyHandle) string

GetPropertyCF returns the value of a database property.

func (*DB) GetUpdatesSince Uses

func (db *DB) GetUpdatesSince(seqNumber uint64) (*WalIterator, error)

func (*DB) IngestExternalFile Uses

func (db *DB) IngestExternalFile(filePaths []string, opts *IngestExternalFileOptions) error

IngestExternalFile loads a list of external SST files.

func (*DB) IngestExternalFileCF Uses

func (db *DB) IngestExternalFileCF(handle *ColumnFamilyHandle, filePaths []string, opts *IngestExternalFileOptions) error

IngestExternalFileCF loads a list of external SST files for a column family.

func (*DB) Merge Uses

func (db *DB) Merge(opts *WriteOptions, key []byte, value []byte) error

Merge merges the data associated with the key with the actual data in the database.

func (*DB) MergeCF Uses

func (db *DB) MergeCF(opts *WriteOptions, cf *ColumnFamilyHandle, key []byte, value []byte) error

MergeCF merges the data associated with the key with the actual data in the database and column family.

func (*DB) MultiGet Uses

func (db *DB) MultiGet(opts *ReadOptions, keys ...[]byte) (Slices, error)

MultiGet returns the data associated with the passed keys from the database

func (*DB) MultiGetCF Uses

func (db *DB) MultiGetCF(opts *ReadOptions, cf *ColumnFamilyHandle, keys ...[]byte) (Slices, error)

MultiGetCF returns the data associated with the passed keys from the column family

func (*DB) MultiGetCFMultiCF Uses

func (db *DB) MultiGetCFMultiCF(opts *ReadOptions, cfs ColumnFamilyHandles, keys [][]byte) (Slices, error)

MultiGetCFMultiCF returns the data associated with the passed keys and column families.

func (*DB) Name Uses

func (db *DB) Name() string

Name returns the name of the database.

func (*DB) NewCheckpoint Uses

func (db *DB) NewCheckpoint() (*Checkpoint, error)

NewCheckpoint creates a new Checkpoint for this db.

func (*DB) NewIterator Uses

func (db *DB) NewIterator(opts *ReadOptions) *Iterator

NewIterator returns an Iterator over the the database that uses the ReadOptions given.

func (*DB) NewIteratorCF Uses

func (db *DB) NewIteratorCF(opts *ReadOptions, cf *ColumnFamilyHandle) *Iterator

NewIteratorCF returns an Iterator over the the database and column family that uses the ReadOptions given.

func (*DB) NewSnapshot Uses

func (db *DB) NewSnapshot() *Snapshot

NewSnapshot creates a new snapshot of the database.

func (*DB) Put Uses

func (db *DB) Put(opts *WriteOptions, key, value []byte) error

Put writes data associated with a key to the database.

func (*DB) PutCF Uses

func (db *DB) PutCF(opts *WriteOptions, cf *ColumnFamilyHandle, key, value []byte) error

PutCF writes data associated with a key to the database and column family.

func (*DB) ReleaseSnapshot Uses

func (db *DB) ReleaseSnapshot(snapshot *Snapshot)

ReleaseSnapshot releases the snapshot and its resources.

func (*DB) SetOptions Uses

func (db *DB) SetOptions(keys, values []string) error

SetOptions dynamically changes options through the SetOptions API.

func (*DB) UnsafeGetDB Uses

func (db *DB) UnsafeGetDB() unsafe.Pointer

UnsafeGetDB returns the underlying c rocksdb instance.

func (*DB) Write Uses

func (db *DB) Write(opts *WriteOptions, batch *WriteBatch) error

Write writes a WriteBatch to the database

type DBPath Uses

type DBPath struct {
    // contains filtered or unexported fields
}

DBPath represents options for a dbpath.

func NewDBPath Uses

func NewDBPath(path string, target_size uint64) *DBPath

NewDBPath creates a DBPath object with the given path and target_size.

func NewDBPathsFromData Uses

func NewDBPathsFromData(paths []string, target_sizes []uint64) []*DBPath

NewDBPathsFromData creates a slice with allocated DBPath objects from paths and target_sizes.

func NewNativeDBPath Uses

func NewNativeDBPath(c *C.rocksdb_dbpath_t) *DBPath

NewNativeDBPath creates a DBPath object.

func (*DBPath) Destroy Uses

func (dbpath *DBPath) Destroy()

Destroy deallocates the DBPath object.

type Env Uses

type Env struct {
    // contains filtered or unexported fields
}

Env is a system call environment used by a database.

func NewDefaultEnv Uses

func NewDefaultEnv() *Env

NewDefaultEnv creates a default environment.

func NewMemEnv Uses

func NewMemEnv() *Env

NewMemEnv creates MemEnv for in-memory testing.

func NewNativeEnv Uses

func NewNativeEnv(c *C.rocksdb_env_t) *Env

NewNativeEnv creates a Environment object.

func (*Env) Destroy Uses

func (env *Env) Destroy()

Destroy deallocates the Env object.

func (*Env) SetBackgroundThreads Uses

func (env *Env) SetBackgroundThreads(n int)

SetBackgroundThreads sets the number of background worker threads of a specific thread pool for this environment. 'LOW' is the default pool. Default: 1

func (*Env) SetHighPriorityBackgroundThreads Uses

func (env *Env) SetHighPriorityBackgroundThreads(n int)

SetHighPriorityBackgroundThreads sets the size of the high priority thread pool that can be used to prevent compactions from stalling memtable flushes.

type EnvOptions Uses

type EnvOptions struct {
    // contains filtered or unexported fields
}

EnvOptions represents options for env.

func NewDefaultEnvOptions Uses

func NewDefaultEnvOptions() *EnvOptions

NewDefaultEnvOptions creates a default EnvOptions object.

func NewNativeEnvOptions Uses

func NewNativeEnvOptions(c *C.rocksdb_envoptions_t) *EnvOptions

NewNativeEnvOptions creates a EnvOptions object.

func (*EnvOptions) Destroy Uses

func (opts *EnvOptions) Destroy()

Destroy deallocates the EnvOptions object.

type FIFOCompactionOptions Uses

type FIFOCompactionOptions struct {
    // contains filtered or unexported fields
}

FIFOCompactionOptions represent all of the available options for FIFO compaction.

func NewDefaultFIFOCompactionOptions Uses

func NewDefaultFIFOCompactionOptions() *FIFOCompactionOptions

NewDefaultFIFOCompactionOptions creates a default FIFOCompactionOptions object.

func NewNativeFIFOCompactionOptions Uses

func NewNativeFIFOCompactionOptions(c *C.rocksdb_fifo_compaction_options_t) *FIFOCompactionOptions

NewNativeFIFOCompactionOptions creates a native FIFOCompactionOptions object.

func (*FIFOCompactionOptions) Destroy Uses

func (opts *FIFOCompactionOptions) Destroy()

Destroy deallocates the FIFOCompactionOptions object.

func (*FIFOCompactionOptions) SetMaxTableFilesSize Uses

func (opts *FIFOCompactionOptions) SetMaxTableFilesSize(value uint64)

SetMaxTableFilesSize sets the max table file size. Once the total sum of table files reaches this, we will delete the oldest table file Default: 1GB

type FilterPolicy Uses

type FilterPolicy interface {
    // keys contains a list of keys (potentially with duplicates)
    // that are ordered according to the user supplied comparator.
    CreateFilter(keys [][]byte) []byte

    // "filter" contains the data appended by a preceding call to
    // CreateFilter(). This method must return true if
    // the key was in the list of keys passed to CreateFilter().
    // This method may return true or false if the key was not on the
    // list, but it should aim to return false with a high probability.
    KeyMayMatch(key []byte, filter []byte) bool

    // Return the name of this policy.
    Name() string
}

FilterPolicy is a factory type that allows the RocksDB database to create a filter, such as a bloom filter, which will used to reduce reads.

func NewBloomFilter Uses

func NewBloomFilter(bitsPerKey int) FilterPolicy

NewBloomFilter returns a new filter policy that uses a bloom filter with approximately the specified number of bits per key. A good value for bits_per_key is 10, which yields a filter with ~1% false positive rate.

Note: if you are using a custom comparator that ignores some parts of the keys being compared, you must not use NewBloomFilterPolicy() and must provide your own FilterPolicy that also ignores the corresponding parts of the keys. For example, if the comparator ignores trailing spaces, it would be incorrect to use a FilterPolicy (like NewBloomFilterPolicy) that does not ignore trailing spaces in keys.

func NewBloomFilterFull Uses

func NewBloomFilterFull(bitsPerKey int) FilterPolicy

NewBloomFilterFull returns a new filter policy created with use_block_based_builder=false (use full or partitioned filter).

func NewNativeFilterPolicy Uses

func NewNativeFilterPolicy(c *C.rocksdb_filterpolicy_t) FilterPolicy

NewNativeFilterPolicy creates a FilterPolicy object.

type FlushOptions Uses

type FlushOptions struct {
    // contains filtered or unexported fields
}

FlushOptions represent all of the available options when manual flushing the database.

func NewDefaultFlushOptions Uses

func NewDefaultFlushOptions() *FlushOptions

NewDefaultFlushOptions creates a default FlushOptions object.

func NewNativeFlushOptions Uses

func NewNativeFlushOptions(c *C.rocksdb_flushoptions_t) *FlushOptions

NewNativeFlushOptions creates a FlushOptions object.

func (*FlushOptions) Destroy Uses

func (opts *FlushOptions) Destroy()

Destroy deallocates the FlushOptions object.

func (*FlushOptions) SetWait Uses

func (opts *FlushOptions) SetWait(value bool)

SetWait specify if the flush will wait until the flush is done. Default: true

type IndexType Uses

type IndexType uint

IndexType specifies the index type that will be used for this table.

type InfoLogLevel Uses

type InfoLogLevel uint

InfoLogLevel describes the log level.

type IngestExternalFileOptions Uses

type IngestExternalFileOptions struct {
    // contains filtered or unexported fields
}

IngestExternalFileOptions represents available options when ingesting external files.

func NewDefaultIngestExternalFileOptions Uses

func NewDefaultIngestExternalFileOptions() *IngestExternalFileOptions

NewDefaultIngestExternalFileOptions creates a default IngestExternalFileOptions object.

func NewNativeIngestExternalFileOptions Uses

func NewNativeIngestExternalFileOptions(c *C.rocksdb_ingestexternalfileoptions_t) *IngestExternalFileOptions

NewNativeIngestExternalFileOptions creates a IngestExternalFileOptions object.

func (*IngestExternalFileOptions) Destroy Uses

func (opts *IngestExternalFileOptions) Destroy()

Destroy deallocates the IngestExternalFileOptions object.

func (*IngestExternalFileOptions) SetAllowBlockingFlush Uses

func (opts *IngestExternalFileOptions) SetAllowBlockingFlush(flag bool)

SetAllowBlockingFlush sets allow_blocking_flush. If set to false and the file key range overlaps with the memtable key range (memtable flush required), IngestExternalFile will fail. Default to true.

func (*IngestExternalFileOptions) SetAllowGlobalSeqNo Uses

func (opts *IngestExternalFileOptions) SetAllowGlobalSeqNo(flag bool)

SetAllowGlobalSeqNo sets allow_global_seqno. If set to false,IngestExternalFile() will fail if the file key range overlaps with existing keys or tombstones in the DB. Default true.

func (*IngestExternalFileOptions) SetIngestionBehind Uses

func (opts *IngestExternalFileOptions) SetIngestionBehind(flag bool)

SetIngestionBehind sets ingest_behind Set to true if you would like duplicate keys in the file being ingested to be skipped rather than overwriting existing data under that key. Usecase: back-fill of some historical data in the database without over-writing existing newer version of data. This option could only be used if the DB has been running with allow_ingest_behind=true since the dawn of time. All files will be ingested at the bottommost level with seqno=0.

func (*IngestExternalFileOptions) SetMoveFiles Uses

func (opts *IngestExternalFileOptions) SetMoveFiles(flag bool)

SetMoveFiles specifies if it should move the files instead of copying them. Default to false.

func (*IngestExternalFileOptions) SetSnapshotConsistency Uses

func (opts *IngestExternalFileOptions) SetSnapshotConsistency(flag bool)

SetSnapshotConsistency if specifies the consistency. If set to false, an ingested file key could appear in existing snapshots that were created before the file was ingested. Default to true.

type Iterator Uses

type Iterator struct {
    // contains filtered or unexported fields
}

Iterator provides a way to seek to specific keys and iterate through the keyspace from that point, as well as access the values of those keys.

For example:

     it := db.NewIterator(readOpts)
     defer it.Close()

     it.Seek([]byte("foo"))
		for ; it.Valid(); it.Next() {
         fmt.Printf("Key: %v Value: %v\n", it.Key().Data(), it.Value().Data())
		}

     if err := it.Err(); err != nil {
         return err
     }

func NewNativeIterator Uses

func NewNativeIterator(c unsafe.Pointer) *Iterator

NewNativeIterator creates a Iterator object.

func (*Iterator) Close Uses

func (iter *Iterator) Close()

Close closes the iterator.

func (*Iterator) Err Uses

func (iter *Iterator) Err() error

Err returns nil if no errors happened during iteration, or the actual error otherwise.

func (*Iterator) Key Uses

func (iter *Iterator) Key() *Slice

Key returns the key the iterator currently holds.

func (*Iterator) Next Uses

func (iter *Iterator) Next()

Next moves the iterator to the next sequential key in the database.

func (*Iterator) Prev Uses

func (iter *Iterator) Prev()

Prev moves the iterator to the previous sequential key in the database.

func (*Iterator) Seek Uses

func (iter *Iterator) Seek(key []byte)

Seek moves the iterator to the position greater than or equal to the key.

func (*Iterator) SeekForPrev Uses

func (iter *Iterator) SeekForPrev(key []byte)

SeekForPrev moves the iterator to the last key that less than or equal to the target key, in contrast with Seek.

func (*Iterator) SeekToFirst Uses

func (iter *Iterator) SeekToFirst()

SeekToFirst moves the iterator to the first key in the database.

func (*Iterator) SeekToLast Uses

func (iter *Iterator) SeekToLast()

SeekToLast moves the iterator to the last key in the database.

func (*Iterator) Valid Uses

func (iter *Iterator) Valid() bool

Valid returns false only when an Iterator has iterated past either the first or the last key in the database.

func (*Iterator) ValidForPrefix Uses

func (iter *Iterator) ValidForPrefix(prefix []byte) bool

ValidForPrefix returns false only when an Iterator has iterated past the first or the last key in the database or the specified prefix.

func (*Iterator) Value Uses

func (iter *Iterator) Value() *Slice

Value returns the value in the database the iterator currently holds.

type LiveFileMetadata Uses

type LiveFileMetadata struct {
    Name        string
    Level       int
    Size        int64
    SmallestKey []byte
    LargestKey  []byte
}

LiveFileMetadata is a metadata which is associated with each SST file.

type MemoryUsage Uses

type MemoryUsage struct {
    // MemTableTotal estimates memory usage of all mem-tables
    MemTableTotal uint64
    // MemTableUnflushed estimates memory usage of unflushed mem-tables
    MemTableUnflushed uint64
    // MemTableReadersTotal memory usage of table readers (indexes and bloom filters)
    MemTableReadersTotal uint64
    // CacheTotal memory usage of cache
    CacheTotal uint64
}

MemoryUsage contains memory usage statistics provided by RocksDB

func GetApproximateMemoryUsageByType Uses

func GetApproximateMemoryUsageByType(dbs []*DB, caches []*Cache) (*MemoryUsage, error)

GetApproximateMemoryUsageByType returns summary memory usage stats for given databases and caches.

type MergeOperator Uses

type MergeOperator interface {
    // Gives the client a way to express the read -> modify -> write semantics
    // key:           The key that's associated with this merge operation.
    //                Client could multiplex the merge operator based on it
    //                if the key space is partitioned and different subspaces
    //                refer to different types of data which have different
    //                merge operation semantics.
    // existingValue: null indicates that the key does not exist before this op.
    // operands:      the sequence of merge operations to apply, front() first.
    //
    // Return true on success.
    //
    // All values passed in will be client-specific values. So if this method
    // returns false, it is because client specified bad data or there was
    // internal corruption. This will be treated as an error by the library.
    FullMerge(key, existingValue []byte, operands [][]byte) ([]byte, bool)

    // The name of the MergeOperator.
    Name() string
}

A MergeOperator specifies the SEMANTICS of a merge, which only client knows. It could be numeric addition, list append, string concatenation, edit data structure, ... , anything. The library, on the other hand, is concerned with the exercise of this interface, at the right time (during get, iteration, compaction...)

Please read the RocksDB documentation <http://rocksdb.org/> for more details and example implementations.

func NewNativeMergeOperator Uses

func NewNativeMergeOperator(c *C.rocksdb_mergeoperator_t) MergeOperator

NewNativeMergeOperator creates a MergeOperator object.

type MultiMerger Uses

type MultiMerger interface {
    // PartialMerge performs merge on multiple operands
    // when all of the operands are themselves merge operation types
    // that you would have passed to a db.Merge() call in the same order
    // (i.e.: db.Merge(key,operand[0]), followed by db.Merge(key,operand[1]),
    // ... db.Merge(key, operand[n])).
    //
    // PartialMerge should combine them into a single merge operation.
    // The return value should be constructed such that a call to
    // db.Merge(key, new_value) would yield the same result as a call
    // to db.Merge(key,operand[0]), followed by db.Merge(key,operand[1]),
    // ... db.Merge(key, operand[n])).
    //
    // If it is impossible or infeasible to combine the operations, return false.
    // The library will internally keep track of the operations, and apply them in the
    // correct order once a base-value (a Put/Delete/End-of-Database) is seen.
    PartialMergeMulti(key []byte, operands [][]byte) ([]byte, bool)
}

MultiMerger implements PartialMergeMulti(key []byte, operands [][]byte) ([]byte, err) When a MergeOperator implements this interface, PartialMergeMulti will be called in addition to FullMerge for compactions across levels

type Options Uses

type Options struct {
    // contains filtered or unexported fields
}

Options represent all of the available options when opening a database with Open.

func GetOptionsFromString Uses

func GetOptionsFromString(base *Options, optStr string) (*Options, error)

GetOptionsFromString creates a Options object from existing opt and string. If base is nil, a default opt create by NewDefaultOptions will be used as base opt.

func NewDefaultOptions Uses

func NewDefaultOptions() *Options

NewDefaultOptions creates the default Options.

func NewNativeOptions Uses

func NewNativeOptions(c *C.rocksdb_options_t) *Options

NewNativeOptions creates a Options object.

func (*Options) Destroy Uses

func (opts *Options) Destroy()

Destroy deallocates the Options object.

func (*Options) EnableStatistics Uses

func (opts *Options) EnableStatistics()

EnableStatistics enable statistics.

func (*Options) GetStatisticsString Uses

func (opts *Options) GetStatisticsString() string

GetStatisticsString returns the statistics as a string.

func (*Options) IncreaseParallelism Uses

func (opts *Options) IncreaseParallelism(total_threads int)

IncreaseParallelism sets the parallelism.

By default, RocksDB uses only one background thread for flush and compaction. Calling this function will set it up such that total of `total_threads` is used. Good value for `total_threads` is the number of cores. You almost definitely want to call this function if your system is bottlenecked by RocksDB.

func (*Options) OptimizeForPointLookup Uses

func (opts *Options) OptimizeForPointLookup(block_cache_size_mb uint64)

OptimizeForPointLookup optimize the DB for point lookups.

Use this if you don't need to keep the data sorted, i.e. you'll never use an iterator, only Put() and Get() API calls

If you use this with rocksdb >= 5.0.2, you must call `SetAllowConcurrentMemtableWrites(false)` to avoid an assertion error immediately on opening the db.

func (*Options) OptimizeLevelStyleCompaction Uses

func (opts *Options) OptimizeLevelStyleCompaction(memtable_memory_budget uint64)

OptimizeLevelStyleCompaction optimize the DB for leveld compaction.

Default values for some parameters in ColumnFamilyOptions are not optimized for heavy workloads and big datasets, which means you might observe write stalls under some conditions. As a starting point for tuning RocksDB options, use the following two functions: * OptimizeLevelStyleCompaction -- optimizes level style compaction * OptimizeUniversalStyleCompaction -- optimizes universal style compaction Universal style compaction is focused on reducing Write Amplification Factor for big data sets, but increases Space Amplification. You can learn more about the different styles here: https://github.com/facebook/rocksdb/wiki/Rocksdb-Architecture-Guide Make sure to also call IncreaseParallelism(), which will provide the biggest performance gains. Note: we might use more memory than memtable_memory_budget during high write rate period

func (*Options) OptimizeUniversalStyleCompaction Uses

func (opts *Options) OptimizeUniversalStyleCompaction(memtable_memory_budget uint64)

OptimizeUniversalStyleCompaction optimize the DB for universal compaction. See note on OptimizeLevelStyleCompaction.

func (*Options) PrepareForBulkLoad Uses

func (opts *Options) PrepareForBulkLoad()

PrepareForBulkLoad prepare the DB for bulk loading.

All data will be in level 0 without any automatic compaction. It's recommended to manually call CompactRange(NULL, NULL) before reading from the database, because otherwise the read can be very slow.

func (*Options) SetAccessHintOnCompactionStart Uses

func (opts *Options) SetAccessHintOnCompactionStart(value CompactionAccessPattern)

SetAccessHintOnCompactionStart specifies the file access pattern once a compaction is started.

It will be applied to all input files of a compaction. Default: NormalCompactionAccessPattern

func (*Options) SetAdviseRandomOnOpen Uses

func (opts *Options) SetAdviseRandomOnOpen(value bool)

SetAdviseRandomOnOpen specifies whether we will hint the underlying file system that the file access pattern is random, when a sst file is opened. Default: true

func (*Options) SetAllowConcurrentMemtableWrites Uses

func (opts *Options) SetAllowConcurrentMemtableWrites(allow bool)

Set whether to allow concurrent memtable writes. Conccurent writes are not supported by all memtable factories (currently only SkipList memtables). As of rocksdb 5.0.2 you must call `SetAllowConcurrentMemtableWrites(false)` if you use `OptimizeForPointLookup`.

func (*Options) SetAllowIngestBehind Uses

func (opts *Options) SetAllowIngestBehind(value bool)

SetAllowIngestBehind sets allow_ingest_behind Set this option to true during creation of database if you want to be able to ingest behind (call IngestExternalFile() skipping keys that already exist, rather than overwriting matching keys). Setting this option to true will affect 2 things: 1) Disable some internal optimizations around SST file compression 2) Reserve bottom-most level for ingested files only. 3) Note that num_levels should be >= 3 if this option is turned on.

DEFAULT: false Immutable.

func (*Options) SetAllowMmapReads Uses

func (opts *Options) SetAllowMmapReads(value bool)

SetAllowMmapReads enable/disable mmap reads for reading sst tables. Default: false

func (*Options) SetAllowMmapWrites Uses

func (opts *Options) SetAllowMmapWrites(value bool)

SetAllowMmapWrites enable/disable mmap writes for writing sst tables. Default: false

func (*Options) SetArenaBlockSize Uses

func (opts *Options) SetArenaBlockSize(value int)

SetArenaBlockSize sets the size of one block in arena memory allocation.

If <= 0, a proper value is automatically calculated (usually 1/10 of writer_buffer_size). Default: 0

func (*Options) SetBlockBasedTableFactory Uses

func (opts *Options) SetBlockBasedTableFactory(value *BlockBasedTableOptions)

SetBlockBasedTableFactory sets the block based table factory.

func (*Options) SetBloomLocality Uses

func (opts *Options) SetBloomLocality(value uint32)

SetBloomLocality sets the bloom locality.

Control locality of bloom filter probes to improve cache miss rate. This option only applies to memtable prefix bloom and plaintable prefix bloom. It essentially limits the max number of cache lines each bloom filter check can touch. This optimization is turned off when set to 0. The number should never be greater than number of probes. This option can boost performance for in-memory workload but should use with care since it can cause higher false positive rate. Default: 0

func (*Options) SetBytesPerSync Uses

func (opts *Options) SetBytesPerSync(value uint64)

SetBytesPerSync sets the bytes per sync.

Allows OS to incrementally sync files to disk while they are being written, asynchronously, in the background. Issue one request for every bytes_per_sync written. Default: 0 (disabled)

func (*Options) SetCompactionFilter Uses

func (opts *Options) SetCompactionFilter(value CompactionFilter)

SetCompactionFilter sets the specified compaction filter which will be applied on compactions. Default: nil

func (*Options) SetCompactionStyle Uses

func (opts *Options) SetCompactionStyle(value CompactionStyle)

SetCompactionStyle sets the compaction style. Default: LevelCompactionStyle

func (*Options) SetComparator Uses

func (opts *Options) SetComparator(value Comparator)

SetComparator sets the comparator which define the order of keys in the table. Default: a comparator that uses lexicographic byte-wise ordering

func (*Options) SetCompression Uses

func (opts *Options) SetCompression(value CompressionType)

SetCompression sets the compression algorithm. Default: SnappyCompression, which gives lightweight but fast compression.

func (*Options) SetCompressionOptions Uses

func (opts *Options) SetCompressionOptions(value *CompressionOptions)

SetCompressionOptions sets different options for compression algorithms. Default: nil

func (*Options) SetCompressionPerLevel Uses

func (opts *Options) SetCompressionPerLevel(value []CompressionType)

SetCompressionPerLevel sets different compression algorithm per level.

Different levels can have different compression policies. There are cases where most lower levels would like to quick compression algorithm while the higher levels (which have more data) use compression algorithms that have better compression but could be slower. This array should have an entry for each level of the database. This array overrides the value specified in the previous field 'compression'.

func (*Options) SetCreateIfMissing Uses

func (opts *Options) SetCreateIfMissing(value bool)

SetCreateIfMissing specifies whether the database should be created if it is missing. Default: false

func (*Options) SetCreateIfMissingColumnFamilies Uses

func (opts *Options) SetCreateIfMissingColumnFamilies(value bool)

SetCreateIfMissingColumnFamilies specifies whether the column families should be created if they are missing.

func (*Options) SetDBPaths Uses

func (opts *Options) SetDBPaths(dbpaths []*DBPath)

SetDBPaths sets the DBPaths of the options.

A list of paths where SST files can be put into, with its target size. Newer data is placed into paths specified earlier in the vector while older data gradually moves to paths specified later in the vector.

For example, you have a flash device with 10GB allocated for the DB, as well as a hard drive of 2TB, you should config it to be:

[{"/flash_path", 10GB}, {"/hard_drive", 2TB}]

The system will try to guarantee data under each path is close to but not larger than the target size. But current and future file sizes used by determining where to place a file are based on best-effort estimation, which means there is a chance that the actual size under the directory is slightly more than target size under some workloads. User should give some buffer room for those cases.

If none of the paths has sufficient room to place a file, the file will be placed to the last path anyway, despite to the target size.

Placing newer data to earlier paths is also best-efforts. User should expect user files to be placed in higher levels in some extreme cases.

If left empty, only one path will be used, which is db_name passed when opening the DB. Default: empty

func (*Options) SetDbLogDir Uses

func (opts *Options) SetDbLogDir(value string)

SetDbLogDir specifies the absolute info LOG dir.

If it is empty, the log files will be in the same dir as data. If it is non empty, the log files will be in the specified dir, and the db data dir's absolute path will be used as the log file name's prefix. Default: empty

func (*Options) SetDbWriteBufferSize Uses

func (opts *Options) SetDbWriteBufferSize(value int)

SetDbWriteBufferSize sets the amount of data to build up in memtables across all column families before writing to disk.

This is distinct from write_buffer_size, which enforces a limit for a single memtable.

This feature is disabled by default. Specify a non-zero value to enable it.

Default: 0 (disabled)

func (*Options) SetDeleteObsoleteFilesPeriodMicros Uses

func (opts *Options) SetDeleteObsoleteFilesPeriodMicros(value uint64)

SetDeleteObsoleteFilesPeriodMicros sets the periodicity when obsolete files get deleted.

The files that get out of scope by compaction process will still get automatically delete on every compaction, regardless of this setting. Default: 6 hours

func (*Options) SetDisableAutoCompactions Uses

func (opts *Options) SetDisableAutoCompactions(value bool)

SetDisableAutoCompactions enable/disable automatic compactions.

Manual compactions can still be issued on this database. Default: false

func (*Options) SetEnablePipelinedWrite Uses

func (opts *Options) SetEnablePipelinedWrite(value bool)

SetEnablePipelinedWrite enables pipelined write

Default: false

func (*Options) SetEnv Uses

func (opts *Options) SetEnv(value *Env)

SetEnv sets the specified object to interact with the environment, e.g. to read/write files, schedule background work, etc. Default: DefaultEnv

func (*Options) SetErrorIfExists Uses

func (opts *Options) SetErrorIfExists(value bool)

SetErrorIfExists specifies whether an error should be raised if the database already exists. Default: false

func (*Options) SetFIFOCompactionOptions Uses

func (opts *Options) SetFIFOCompactionOptions(value *FIFOCompactionOptions)

SetFIFOCompactionOptions sets the options for FIFO compaction style. Default: nil

func (*Options) SetHardPendingCompactionBytesLimit Uses

func (opts *Options) SetHardPendingCompactionBytesLimit(value uint64)

SetHardPendingCompactionBytesLimit sets the bytes threshold at which all writes are stopped if estimated bytes needed to be compaction exceed this threshold.

Default: 256GB

func (*Options) SetHardRateLimit Uses

func (opts *Options) SetHardRateLimit(value float64)

SetHardRateLimit sets the hard rate limit.

Puts are delayed 1ms at a time when any level has a compaction score that exceeds hard_rate_limit. This is ignored when <= 1.0. Default: 0.0 (disabled)

func (*Options) SetHashLinkListRep Uses

func (opts *Options) SetHashLinkListRep(bucketCount int)

SetHashLinkListRep sets a hashed linked list as MemTableRep.

It contains a fixed array of buckets, each pointing to a sorted single linked list (null if the bucket is empty).

bucketCount: number of fixed array buckets

func (*Options) SetHashSkipListRep Uses

func (opts *Options) SetHashSkipListRep(bucketCount int, skiplistHeight, skiplistBranchingFactor int32)

SetHashSkipListRep sets a hash skip list as MemTableRep.

It contains a fixed array of buckets, each pointing to a skiplist (null if the bucket is empty).

bucketCount: number of fixed array buckets skiplistHeight: the max height of the skiplist skiplistBranchingFactor: probabilistic size ratio between adjacent

link lists in the skiplist

func (*Options) SetInfoLogLevel Uses

func (opts *Options) SetInfoLogLevel(value InfoLogLevel)

SetInfoLogLevel sets the info log level. Default: InfoInfoLogLevel

func (*Options) SetInplaceUpdateNumLocks Uses

func (opts *Options) SetInplaceUpdateNumLocks(value int)

SetInplaceUpdateNumLocks sets the number of locks used for inplace update. Default: 10000, if inplace_update_support = true, else 0.

func (*Options) SetInplaceUpdateSupport Uses

func (opts *Options) SetInplaceUpdateSupport(value bool)

SetInplaceUpdateSupport enable/disable thread-safe inplace updates.

Requires updates if * key exists in current memtable * new sizeof(new_value) <= sizeof(old_value) * old_value for that key is a put i.e. kTypeValue Default: false.

func (*Options) SetIsFdCloseOnExec Uses

func (opts *Options) SetIsFdCloseOnExec(value bool)

SetIsFdCloseOnExec enable/dsiable child process inherit open files. Default: true

func (*Options) SetKeepLogFileNum Uses

func (opts *Options) SetKeepLogFileNum(value int)

SetKeepLogFileNum sets the maximal info log files to be kept. Default: 1000

func (*Options) SetLevel0FileNumCompactionTrigger Uses

func (opts *Options) SetLevel0FileNumCompactionTrigger(value int)

SetLevel0FileNumCompactionTrigger sets the number of files to trigger level-0 compaction.

A value <0 means that level-0 compaction will not be triggered by number of files at all. Default: 4

func (*Options) SetLevel0SlowdownWritesTrigger Uses

func (opts *Options) SetLevel0SlowdownWritesTrigger(value int)

SetLevel0SlowdownWritesTrigger sets the soft limit on number of level-0 files.

We start slowing down writes at this point. A value <0 means that no writing slow down will be triggered by number of files in level-0. Default: 8

func (*Options) SetLevel0StopWritesTrigger Uses

func (opts *Options) SetLevel0StopWritesTrigger(value int)

SetLevel0StopWritesTrigger sets the maximum number of level-0 files. We stop writes at this point. Default: 12

func (*Options) SetLevelCompactionDynamicLevelBytes Uses

func (opts *Options) SetLevelCompactionDynamicLevelBytes(value bool)

SetLevelCompactiondynamiclevelbytes specifies whether to pick target size of each level dynamically.

We will pick a base level b >= 1. L0 will be directly merged into level b, instead of always into level 1. Level 1 to b-1 need to be empty. We try to pick b and its target size so that 1. target size is in the range of

(max_bytes_for_level_base / max_bytes_for_level_multiplier,
 max_bytes_for_level_base]

2. target size of the last level (level num_levels-1) equals to extra size

of the level.

At the same time max_bytes_for_level_multiplier and max_bytes_for_level_multiplier_additional are still satisfied.

With this option on, from an empty DB, we make last level the base level, which means merging L0 data into the last level, until it exceeds max_bytes_for_level_base. And then we make the second last level to be base level, to start to merge L0 data to second last level, with its target size to be 1/max_bytes_for_level_multiplier of the last level's extra size. After the data accumulates more so that we need to move the base level to the third last one, and so on.

For example, assume max_bytes_for_level_multiplier=10, num_levels=6, and max_bytes_for_level_base=10MB. Target sizes of level 1 to 5 starts with: [- - - - 10MB] with base level is level. Target sizes of level 1 to 4 are not applicable because they will not be used. Until the size of Level 5 grows to more than 10MB, say 11MB, we make base target to level 4 and now the targets looks like: [- - - 1.1MB 11MB] While data are accumulated, size targets are tuned based on actual data of level 5. When level 5 has 50MB of data, the target is like: [- - - 5MB 50MB] Until level 5's actual size is more than 100MB, say 101MB. Now if we keep level 4 to be the base level, its target size needs to be 10.1MB, which doesn't satisfy the target size range. So now we make level 3 the target size and the target sizes of the levels look like: [- - 1.01MB 10.1MB 101MB] In the same way, while level 5 further grows, all levels' targets grow, like [- - 5MB 50MB 500MB] Until level 5 exceeds 1000MB and becomes 1001MB, we make level 2 the base level and make levels' target sizes like this: [- 1.001MB 10.01MB 100.1MB 1001MB] and go on...

By doing it, we give max_bytes_for_level_multiplier a priority against max_bytes_for_level_base, for a more predictable LSM tree shape. It is useful to limit worse case space amplification.

max_bytes_for_level_multiplier_additional is ignored with this flag on.

Turning this feature on or off for an existing DB can cause unexpected LSM tree structure so it's not recommended.

Default: false

func (*Options) SetLogFileTimeToRoll Uses

func (opts *Options) SetLogFileTimeToRoll(value int)

SetLogFileTimeToRoll sets the time for the info log file to roll (in seconds).

If specified with non-zero value, log file will be rolled if it has been active longer than `log_file_time_to_roll`. Default: 0 (disabled)

func (*Options) SetManifestPreallocationSize Uses

func (opts *Options) SetManifestPreallocationSize(value int)

SetManifestPreallocationSize sets the number of bytes to preallocate (via fallocate) the manifest files.

Default is 4mb, which is reasonable to reduce random IO as well as prevent overallocation for mounts that preallocate large amounts of data (such as xfs's allocsize option). Default: 4mb

func (*Options) SetMaxBackgroundCompactions Uses

func (opts *Options) SetMaxBackgroundCompactions(value int)

SetMaxBackgroundCompactions sets the maximum number of concurrent background jobs, submitted to the default LOW priority thread pool Default: 1

func (*Options) SetMaxBackgroundFlushes Uses

func (opts *Options) SetMaxBackgroundFlushes(value int)

SetMaxBackgroundFlushes sets the maximum number of concurrent background memtable flush jobs, submitted to the HIGH priority thread pool.

By default, all background jobs (major compaction and memtable flush) go to the LOW priority pool. If this option is set to a positive number, memtable flush jobs will be submitted to the HIGH priority pool. It is important when the same Env is shared by multiple db instances. Without a separate pool, long running major compaction jobs could potentially block memtable flush jobs of other db instances, leading to unnecessary Put stalls. Default: 0

func (*Options) SetMaxBytesForLevelBase Uses

func (opts *Options) SetMaxBytesForLevelBase(value uint64)

SetMaxBytesForLevelBase sets the maximum total data size for a level.

It is the max total for level-1. Maximum number of bytes for level L can be calculated as (max_bytes_for_level_base) * (max_bytes_for_level_multiplier ^ (L-1))

For example, if max_bytes_for_level_base is 20MB, and if max_bytes_for_level_multiplier is 10, total data size for level-1 will be 20MB, total file size for level-2 will be 200MB, and total file size for level-3 will be 2GB. Default: 10MB

func (*Options) SetMaxBytesForLevelMultiplier Uses

func (opts *Options) SetMaxBytesForLevelMultiplier(value float64)

SetMaxBytesForLevelMultiplier sets the max Bytes for level multiplier. Default: 10

func (*Options) SetMaxBytesForLevelMultiplierAdditional Uses

func (opts *Options) SetMaxBytesForLevelMultiplierAdditional(value []int)

SetMaxBytesForLevelMultiplierAdditional sets different max-size multipliers for different levels.

These are multiplied by max_bytes_for_level_multiplier to arrive at the max-size of each level. Default: 1 for each level

func (*Options) SetMaxCompactionBytes Uses

func (opts *Options) SetMaxCompactionBytes(value uint64)

SetMaxCompactionBytes sets the maximum number of bytes in all compacted files. We try to limit number of bytes in one compaction to be lower than this threshold. But it's not guaranteed. Value 0 will be sanitized. Default: result.target_file_size_base * 25

func (*Options) SetMaxFileOpeningThreads Uses

func (opts *Options) SetMaxFileOpeningThreads(value int)

SetMaxFileOpeningThreads sets the maximum number of file opening threads. If max_open_files is -1, DB will open all files on DB::Open(). You can use this option to increase the number of threads used to open the files. Default: 16

func (*Options) SetMaxLogFileSize Uses

func (opts *Options) SetMaxLogFileSize(value int)

SetMaxLogFileSize sets the maximal size of the info log file.

If the log file is larger than `max_log_file_size`, a new info log file will be created. If max_log_file_size == 0, all logs will be written to one log file. Default: 0

func (*Options) SetMaxManifestFileSize Uses

func (opts *Options) SetMaxManifestFileSize(value uint64)

SetMaxManifestFileSize sets the maximal manifest file size until is rolled over. The older manifest file be deleted. Default: MAX_INT so that roll-over does not take place.

func (*Options) SetMaxMemCompactionLevel Uses

func (opts *Options) SetMaxMemCompactionLevel(value int)

SetMaxMemCompactionLevel sets the maximum level to which a new compacted memtable is pushed if it does not create overlap.

We try to push to level 2 to avoid the relatively expensive level 0=>1 compactions and to avoid some expensive manifest file operations. We do not push all the way to the largest level since that can generate a lot of wasted disk space if the same key space is being repeatedly overwritten. Default: 2

func (*Options) SetMaxOpenFiles Uses

func (opts *Options) SetMaxOpenFiles(value int)

SetMaxOpenFiles sets the number of open files that can be used by the DB.

You may need to increase this if your database has a large working set (budget one open file per 2MB of working set). Default: 1000

func (*Options) SetMaxSequentialSkipInIterations Uses

func (opts *Options) SetMaxSequentialSkipInIterations(value uint64)

SetMaxSequentialSkipInIterations specifies whether an iteration->Next() sequentially skips over keys with the same user-key or not.

This number specifies the number of keys (with the same userkey) that will be sequentially skipped before a reseek is issued. Default: 8

func (*Options) SetMaxSuccessiveMerges Uses

func (opts *Options) SetMaxSuccessiveMerges(value int)

SetMaxSuccessiveMerges sets the maximum number of successive merge operations on a key in the memtable.

When a merge operation is added to the memtable and the maximum number of successive merges is reached, the value of the key will be calculated and inserted into the memtable instead of the merge operation. This will ensure that there are never more than max_successive_merges merge operations in the memtable. Default: 0 (disabled)

func (*Options) SetMaxTotalWalSize Uses

func (opts *Options) SetMaxTotalWalSize(value uint64)

SetMaxTotalWalSize sets the maximum total wal size in bytes. Once write-ahead logs exceed this size, we will start forcing the flush of column families whose memtables are backed by the oldest live WAL file (i.e. the ones that are causing all the space amplification). If set to 0 (default), we will dynamically choose the WAL size limit to be [sum of all write_buffer_size * max_write_buffer_number] * 4 Default: 0

func (*Options) SetMaxWriteBufferNumber Uses

func (opts *Options) SetMaxWriteBufferNumber(value int)

SetMaxWriteBufferNumber sets the maximum number of write buffers that are built up in memory.

The default is 2, so that when 1 write buffer is being flushed to storage, new writes can continue to the other write buffer. Default: 2

func (*Options) SetMemTablePrefixBloomSizeRatio Uses

func (opts *Options) SetMemTablePrefixBloomSizeRatio(value float64)

SetMemTablePrefixBloomSizeRatio sets memtable_prefix_bloom_size_ratio if prefix_extractor is set and memtable_prefix_bloom_size_ratio is not 0, create prefix bloom for memtable with the size of write_buffer_size * memtable_prefix_bloom_size_ratio. If it is larger than 0.25, it is sanitized to 0.25.

Default: 0 (disable)

func (*Options) SetMemtableHugePageSize Uses

func (opts *Options) SetMemtableHugePageSize(value int)

SetMemtableHugePageSize sets the page size for huge page for arena used by the memtable. If <=0, it won't allocate from huge page but from malloc. Users are responsible to reserve huge pages for it to be allocated. For example:

sysctl -w vm.nr_hugepages=20

See linux doc Documentation/vm/hugetlbpage.txt If there isn't enough free huge page available, it will fall back to malloc.

Dynamically changeable through SetOptions() API

func (*Options) SetMemtableVectorRep Uses

func (opts *Options) SetMemtableVectorRep()

SetMemtableVectorRep sets a MemTableRep which is backed by a vector.

On iteration, the vector is sorted. This is useful for workloads where iteration is very rare and writes are generally not issued after reads begin.

func (*Options) SetMergeOperator Uses

func (opts *Options) SetMergeOperator(value MergeOperator)

SetMergeOperator sets the merge operator which will be called if a merge operations are used. Default: nil

func (*Options) SetMinLevelToCompress Uses

func (opts *Options) SetMinLevelToCompress(value int)

SetMinLevelToCompress sets the start level to use compression.

func (*Options) SetMinWriteBufferNumberToMerge Uses

func (opts *Options) SetMinWriteBufferNumberToMerge(value int)

SetMinWriteBufferNumberToMerge sets the minimum number of write buffers that will be merged together before writing to storage.

If set to 1, then all write buffers are flushed to L0 as individual files and this increases read amplification because a get request has to check in all of these files. Also, an in-memory merge may result in writing lesser data to storage if there are duplicate records in each of these individual write buffers. Default: 1

func (*Options) SetNumLevels Uses

func (opts *Options) SetNumLevels(value int)

SetNumLevels sets the number of levels for this database. Default: 7

func (*Options) SetOptimizeFiltersForHits Uses

func (opts *Options) SetOptimizeFiltersForHits(value bool)

SetOptimizeFiltersForHits sets optimize_filters_for_hits This flag specifies that the implementation should optimize the filters mainly for cases where keys are found rather than also optimize for keys missed. This would be used in cases where the application knows that there are very few misses or the performance in the case of misses is not important.

For now, this flag allows us to not store filters for the last level i.e the largest level which contains data of the LSM store. For keys which are hits, the filters in this level are not useful because we will search for the data anyway. NOTE: the filters in other levels are still useful even for key hit because they tell us whether to look in that level or go to the higher level.

Default: false

func (*Options) SetParanoidChecks Uses

func (opts *Options) SetParanoidChecks(value bool)

SetParanoidChecks enable/disable paranoid checks.

If true, the implementation will do aggressive checking of the data it is processing and will stop early if it detects any errors. This may have unforeseen ramifications: for example, a corruption of one DB entry may cause a large number of entries to become unreadable or for the entire DB to become unopenable. If any of the writes to the database fails (Put, Delete, Merge, Write), the database will switch to read-only mode and fail all other Write operations. Default: false

func (*Options) SetPlainTableFactory Uses

func (opts *Options) SetPlainTableFactory(keyLen uint32, bloomBitsPerKey int, hashTableRatio float64, indexSparseness int)

SetPlainTableFactory sets a plain table factory with prefix-only seek.

For this factory, you need to set prefix_extractor properly to make it work. Look-up will starts with prefix hash lookup for key prefix. Inside the hash bucket found, a binary search is executed for hash conflicts. Finally, a linear search is used.

keyLen: plain table has optimization for fix-sized keys,

which can be specified via keyLen.

bloomBitsPerKey: the number of bits used for bloom filer per prefix. You

may disable it by passing a zero.

hashTableRatio: the desired utilization of the hash table used for prefix

hashing. hashTableRatio = number of prefixes / #buckets
in the hash table

indexSparseness: inside each prefix, need to build one index record for how

many keys for binary search inside each hash bucket.

func (*Options) SetPrefixExtractor Uses

func (opts *Options) SetPrefixExtractor(value SliceTransform)

SetPrefixExtractor sets the prefic extractor.

If set, use the specified function to determine the prefixes for keys. These prefixes will be placed in the filter. Depending on the workload, this can reduce the number of read-IOP cost for scans when a prefix is passed via ReadOptions to db.NewIterator(). Default: nil

func (*Options) SetPurgeRedundantKvsWhileFlush Uses

func (opts *Options) SetPurgeRedundantKvsWhileFlush(value bool)

SetPurgeRedundantKvsWhileFlush enable/disable purging of duplicate/deleted keys when a memtable is flushed to storage. Default: true

func (*Options) SetRateLimitDelayMaxMilliseconds Uses

func (opts *Options) SetRateLimitDelayMaxMilliseconds(value uint)

SetRateLimitDelayMaxMilliseconds sets the max time a put will be stalled when hard_rate_limit is enforced. If 0, then there is no limit. Default: 1000

func (*Options) SetRateLimiter Uses

func (opts *Options) SetRateLimiter(rateLimiter *RateLimiter)

SetRateLimiter sets the rate limiter of the options. Use to control write rate of flush and compaction. Flush has higher priority than compaction. Rate limiting is disabled if nullptr. If rate limiter is enabled, bytes_per_sync is set to 1MB by default. Default: nullptr

func (*Options) SetSkipLogErrorOnRecovery Uses

func (opts *Options) SetSkipLogErrorOnRecovery(value bool)

SetSkipLogErrorOnRecovery enable/disable skipping of log corruption error on recovery (If client is ok with losing most recent changes) Default: false

func (*Options) SetSoftPendingCompactionBytesLimit Uses

func (opts *Options) SetSoftPendingCompactionBytesLimit(value uint64)

SetSoftPendingCompactionBytesLimit sets the threshold at which all writes will be slowed down to at least delayed_write_rate if estimated bytes needed to be compaction exceed this threshold.

Default: 64GB

func (*Options) SetSoftRateLimit Uses

func (opts *Options) SetSoftRateLimit(value float64)

SetSoftRateLimit sets the soft rate limit.

Puts are delayed 0-1 ms when any level has a compaction score that exceeds soft_rate_limit. This is ignored when == 0.0. CONSTRAINT: soft_rate_limit <= hard_rate_limit. If this constraint does not hold, RocksDB will set soft_rate_limit = hard_rate_limit Default: 0.0 (disabled)

func (*Options) SetStatsDumpPeriodSec Uses

func (opts *Options) SetStatsDumpPeriodSec(value uint)

SetStatsDumpPeriodSec sets the stats dump period in seconds.

If not zero, dump stats to LOG every stats_dump_period_sec Default: 3600 (1 hour)

func (*Options) SetTableCacheNumshardbits Uses

func (opts *Options) SetTableCacheNumshardbits(value int)

SetTableCacheNumshardbits sets the number of shards used for table cache. Default: 4

func (*Options) SetTableCacheRemoveScanCountLimit Uses

func (opts *Options) SetTableCacheRemoveScanCountLimit(value int)

SetTableCacheRemoveScanCountLimit sets the count limit during a scan.

During data eviction of table's LRU cache, it would be inefficient to strictly follow LRU because this piece of memory will not really be released unless its refcount falls to zero. Instead, make two passes: the first pass will release items with refcount = 1, and if not enough space releases after scanning the number of elements specified by this parameter, we will remove items in LRU order. Default: 16

func (*Options) SetTargetFileSizeBase Uses

func (opts *Options) SetTargetFileSizeBase(value uint64)

SetTargetFileSizeBase sets the target file size for compaction.

Target file size is per-file size for level-1. Target file size for level L can be calculated by target_file_size_base * (target_file_size_multiplier ^ (L-1))

For example, if target_file_size_base is 2MB and target_file_size_multiplier is 10, then each file on level-1 will be 2MB, and each file on level 2 will be 20MB, and each file on level-3 will be 200MB. Default: 2MB

func (*Options) SetTargetFileSizeMultiplier Uses

func (opts *Options) SetTargetFileSizeMultiplier(value int)

SetTargetFileSizeMultiplier sets the target file size multiplier for compaction. Default: 1

func (*Options) SetUniversalCompactionOptions Uses

func (opts *Options) SetUniversalCompactionOptions(value *UniversalCompactionOptions)

SetUniversalCompactionOptions sets the options needed to support Universal Style compactions. Default: nil

func (*Options) SetUseAdaptiveMutex Uses

func (opts *Options) SetUseAdaptiveMutex(value bool)

SetUseAdaptiveMutex enable/disable adaptive mutex, which spins in the user space before resorting to kernel.

This could reduce context switch when the mutex is not heavily contended. However, if the mutex is hot, we could end up wasting spin time. Default: false

func (*Options) SetUseDirectIOForFlushAndCompaction Uses

func (opts *Options) SetUseDirectIOForFlushAndCompaction(value bool)

SetUseDirectIOForFlushAndCompaction enable/disable direct I/O mode (O_DIRECT) for both reads and writes in background flush and compactions When true, new_table_reader_for_compaction_inputs is forced to true. Default: false

func (*Options) SetUseDirectReads Uses

func (opts *Options) SetUseDirectReads(value bool)

SetUseDirectReads enable/disable direct I/O mode (O_DIRECT) for reads Default: false

func (*Options) SetUseFsync Uses

func (opts *Options) SetUseFsync(value bool)

SetUseFsync enable/disable fsync.

If true, then every store to stable storage will issue a fsync. If false, then every store to stable storage will issue a fdatasync. This parameter should be set to true while storing data to filesystem like ext3 that can lose files after a reboot. Default: false

func (*Options) SetWALRecoveryMode Uses

func (opts *Options) SetWALRecoveryMode(mode WALRecoveryMode)

SetWALRecoveryMode sets the recovery mode

Recovery mode to control the consistency while replaying WAL Default: TolerateCorruptedTailRecordsRecovery

func (*Options) SetWALTtlSeconds Uses

func (opts *Options) SetWALTtlSeconds(value uint64)

SetWALTtlSeconds sets the WAL ttl in seconds.

The following two options affect how archived logs will be deleted. 1. If both set to 0, logs will be deleted asap and will not get into

the archive.

2. If wal_ttl_seconds is 0 and wal_size_limit_mb is not 0,

WAL files will be checked every 10 min and if total size is greater
then wal_size_limit_mb, they will be deleted starting with the
earliest until size_limit is met. All empty files will be deleted.

3. If wal_ttl_seconds is not 0 and wall_size_limit_mb is 0, then

WAL files will be checked every wal_ttl_seconds / 2 and those that
are older than wal_ttl_seconds will be deleted.

4. If both are not 0, WAL files will be checked every 10 min and both

checks will be performed with ttl being first.

Default: 0

func (*Options) SetWalDir Uses

func (opts *Options) SetWalDir(value string)

SetWalDir specifies the absolute dir path for write-ahead logs (WAL).

If it is empty, the log files will be in the same dir as data. If it is non empty, the log files will be in the specified dir, When destroying the db, all log files and the dir itopts is deleted. Default: empty

func (*Options) SetWalSizeLimitMb Uses

func (opts *Options) SetWalSizeLimitMb(value uint64)

SetWalSizeLimitMb sets the WAL size limit in MB.

If total size of WAL files is greater then wal_size_limit_mb, they will be deleted starting with the earliest until size_limit is met Default: 0

func (*Options) SetWriteBufferSize Uses

func (opts *Options) SetWriteBufferSize(value int)

SetWriteBufferSize sets the amount of data to build up in memory (backed by an unsorted log on disk) before converting to a sorted on-disk file.

Larger values increase performance, especially during bulk loads. Up to max_write_buffer_number write buffers may be held in memory at the same time, so you may wish to adjust this parameter to control memory usage. Also, a larger write buffer will result in a longer recovery time the next time the database is opened. Default: 64MB

type PartialMerger Uses

type PartialMerger interface {
    // This function performs merge(left_op, right_op)
    // when both the operands are themselves merge operation types
    // that you would have passed to a db.Merge() call in the same order
    // (i.e.: db.Merge(key,left_op), followed by db.Merge(key,right_op)).
    //
    // PartialMerge should combine them into a single merge operation.
    // The return value should be constructed such that a call to
    // db.Merge(key, new_value) would yield the same result as a call
    // to db.Merge(key, left_op) followed by db.Merge(key, right_op).
    //
    // If it is impossible or infeasible to combine the two operations, return false.
    // The library will internally keep track of the operations, and apply them in the
    // correct order once a base-value (a Put/Delete/End-of-Database) is seen.
    PartialMerge(key, leftOperand, rightOperand []byte) ([]byte, bool)
}

PartialMerger implements PartialMerge(key, leftOperand, rightOperand []byte) ([]byte, err) When a MergeOperator implements this interface, PartialMerge will be called in addition to FullMerge for compactions across levels

type PinnableSliceHandle Uses

type PinnableSliceHandle struct {
    // contains filtered or unexported fields
}

PinnableSliceHandle represents a handle to a PinnableSlice.

func NewNativePinnableSliceHandle Uses

func NewNativePinnableSliceHandle(c *C.rocksdb_pinnableslice_t) *PinnableSliceHandle

NewNativePinnableSliceHandle creates a PinnableSliceHandle object.

func (*PinnableSliceHandle) Data Uses

func (h *PinnableSliceHandle) Data() []byte

Data returns the data of the slice.

func (*PinnableSliceHandle) Destroy Uses

func (h *PinnableSliceHandle) Destroy()

Destroy calls the destructor of the underlying pinnable slice handle.

type Range Uses

type Range struct {
    Start []byte
    Limit []byte
}

Range is a range of keys in the database. GetApproximateSizes calls with it begin at the key Start and end right before the key Limit.

type RateLimiter Uses

type RateLimiter struct {
    // contains filtered or unexported fields
}

RateLimiter, is used to control write rate of flush and compaction.

func NewNativeRateLimiter Uses

func NewNativeRateLimiter(c *C.rocksdb_ratelimiter_t) *RateLimiter

NewNativeRateLimiter creates a native RateLimiter object.

func NewRateLimiter Uses

func NewRateLimiter(rate_bytes_per_sec, refill_period_us int64, fairness int32) *RateLimiter

NewDefaultRateLimiter creates a default RateLimiter object.

func (*RateLimiter) Destroy Uses

func (self *RateLimiter) Destroy()

Destroy deallocates the RateLimiter object.

type ReadOptions Uses

type ReadOptions struct {
    // contains filtered or unexported fields
}

ReadOptions represent all of the available options when reading from a database.

func NewDefaultReadOptions Uses

func NewDefaultReadOptions() *ReadOptions

NewDefaultReadOptions creates a default ReadOptions object.

func NewNativeReadOptions Uses

func NewNativeReadOptions(c *C.rocksdb_readoptions_t) *ReadOptions

NewNativeReadOptions creates a ReadOptions object.

func (*ReadOptions) Destroy Uses

func (opts *ReadOptions) Destroy()

Destroy deallocates the ReadOptions object.

func (*ReadOptions) SetFillCache Uses

func (opts *ReadOptions) SetFillCache(value bool)

SetFillCache specify whether the "data block"/"index block"/"filter block" read for this iteration should be cached in memory? Callers may wish to set this field to false for bulk scans. Default: true

func (*ReadOptions) SetIterateUpperBound Uses

func (opts *ReadOptions) SetIterateUpperBound(key []byte)

SetIterateUpperBound specifies "iterate_upper_bound", which defines the extent upto which the forward iterator can returns entries. Once the bound is reached, Valid() will be false. "iterate_upper_bound" is exclusive ie the bound value is not a valid entry. If iterator_extractor is not null, the Seek target and iterator_upper_bound need to have the same prefix. This is because ordering is not guaranteed outside of prefix domain. There is no lower bound on the iterator. If needed, that can be easily implemented. Default: nullptr

func (*ReadOptions) SetPinData Uses

func (opts *ReadOptions) SetPinData(value bool)

SetPinData specifies the value of "pin_data". If true, it keeps the blocks loaded by the iterator pinned in memory as long as the iterator is not deleted, If used when reading from tables created with BlockBasedTableOptions::use_delta_encoding = false, Iterator's property "rocksdb.iterator.is-key-pinned" is guaranteed to return 1. Default: false

func (*ReadOptions) SetPrefixSameAsStart Uses

func (opts *ReadOptions) SetPrefixSameAsStart(value bool)

SetPrefixSameAsStart Enforce that the iterator only iterates over the same prefix as the seek. This option is effective only for prefix seeks, i.e. prefix_extractor is non-null for the column family and total_order_seek is false. Unlike iterate_upper_bound, prefix_same_as_start only works within a prefix but in both directions. Default: false

func (*ReadOptions) SetReadTier Uses

func (opts *ReadOptions) SetReadTier(value ReadTier)

SetReadTier specify if this read request should process data that ALREADY resides on a particular cache. If the required data is not found at the specified cache, then Status::Incomplete is returned. Default: ReadAllTier

func (*ReadOptions) SetReadaheadSize Uses

func (opts *ReadOptions) SetReadaheadSize(value uint64)

SetReadaheadSize specifies the value of "readahead_size". If non-zero, NewIterator will create a new table reader which performs reads of the given size. Using a large size (> 2MB) can improve the performance of forward iteration on spinning disks. Default: 0

func (*ReadOptions) SetSnapshot Uses

func (opts *ReadOptions) SetSnapshot(snap *Snapshot)

SetSnapshot sets the snapshot which should be used for the read. The snapshot must belong to the DB that is being read and must not have been released. Default: nil

func (*ReadOptions) SetTailing Uses

func (opts *ReadOptions) SetTailing(value bool)

SetTailing specify if to create a tailing iterator. A special iterator that has a view of the complete database (i.e. it can also be used to read newly added data) and is optimized for sequential reads. It will return records that were inserted into the database after the creation of the iterator. Default: false

func (*ReadOptions) SetVerifyChecksums Uses

func (opts *ReadOptions) SetVerifyChecksums(value bool)

SetVerifyChecksums speciy if all data read from underlying storage will be verified against corresponding checksums. Default: false

func (*ReadOptions) UnsafeGetReadOptions Uses

func (opts *ReadOptions) UnsafeGetReadOptions() unsafe.Pointer

UnsafeGetReadOptions returns the underlying c read options object.

type ReadTier Uses

type ReadTier uint

ReadTier controls fetching of data during a read request. An application can issue a read request (via Get/Iterators) and specify if that read should process data that ALREADY resides on a specified cache level. For example, if an application specifies BlockCacheTier then the Get call will process data that is already processed in the memtable or the block cache. It will not page in data from the OS cache or data that resides in storage.

type RestoreOptions Uses

type RestoreOptions struct {
    // contains filtered or unexported fields
}

RestoreOptions captures the options to be used during restoration of a backup.

func NewRestoreOptions Uses

func NewRestoreOptions() *RestoreOptions

NewRestoreOptions creates a RestoreOptions instance.

func (*RestoreOptions) Destroy Uses

func (ro *RestoreOptions) Destroy()

Destroy destroys this RestoreOptions instance.

func (*RestoreOptions) SetKeepLogFiles Uses

func (ro *RestoreOptions) SetKeepLogFiles(v int)

SetKeepLogFiles is used to set or unset the keep_log_files option If true, restore won't overwrite the existing log files in wal_dir. It will also move all log files from archive directory to wal_dir. By default, this is false.

type SSTFileWriter Uses

type SSTFileWriter struct {
    // contains filtered or unexported fields
}

SSTFileWriter is used to create sst files that can be added to database later. All keys in files generated by SstFileWriter will have sequence number = 0.

func NewSSTFileWriter Uses

func NewSSTFileWriter(opts *EnvOptions, dbOpts *Options) *SSTFileWriter

NewSSTFileWriter creates an SSTFileWriter object.

func (*SSTFileWriter) Add Uses

func (w *SSTFileWriter) Add(key, value []byte) error

Add adds key, value to currently opened file. REQUIRES: key is after any previously added key according to comparator.

func (*SSTFileWriter) Destroy Uses

func (w *SSTFileWriter) Destroy()

Destroy destroys the SSTFileWriter object.

func (*SSTFileWriter) Finish Uses

func (w *SSTFileWriter) Finish() error

Finish finishes writing to sst file and close file.

func (*SSTFileWriter) Open Uses

func (w *SSTFileWriter) Open(path string) error

Open prepares SstFileWriter to write into file located at "path".

type Slice Uses

type Slice struct {
    // contains filtered or unexported fields
}

Slice is used as a wrapper for non-copy values

func NewSlice Uses

func NewSlice(data *C.char, size C.size_t) *Slice

NewSlice returns a slice with the given data.

func StringToSlice Uses

func StringToSlice(data string) *Slice

StringToSlice is similar to NewSlice, but can be called with a Go string type. This exists to make testing integration with Gorocksdb easier.

func (*Slice) Data Uses

func (s *Slice) Data() []byte

Data returns the data of the slice. If the key doesn't exist this will be a nil slice.

func (*Slice) Exists Uses

func (s *Slice) Exists() bool

Exists returns if the key exists

func (*Slice) Free Uses

func (s *Slice) Free()

Free frees the slice data.

func (*Slice) Size Uses

func (s *Slice) Size() int

Size returns the size of the data.

type SliceTransform Uses

type SliceTransform interface {
    // Transform a src in domain to a dst in the range.
    Transform(src []byte) []byte

    // Determine whether this is a valid src upon the function applies.
    InDomain(src []byte) bool

    // Determine whether dst=Transform(src) for some src.
    InRange(src []byte) bool

    // Return the name of this transformation.
    Name() string
}

A SliceTransform can be used as a prefix extractor.

func NewFixedPrefixTransform Uses

func NewFixedPrefixTransform(prefixLen int) SliceTransform

NewFixedPrefixTransform creates a new fixed prefix transform.

func NewNativeSliceTransform Uses

func NewNativeSliceTransform(c *C.rocksdb_slicetransform_t) SliceTransform

NewNativeSliceTransform creates a SliceTransform object.

func NewNoopPrefixTransform Uses

func NewNoopPrefixTransform() SliceTransform

NewNoopPrefixTransform creates a new no-op prefix transform.

type Slices Uses

type Slices []*Slice

func (Slices) Destroy Uses

func (slices Slices) Destroy()

type Snapshot Uses

type Snapshot struct {
    // contains filtered or unexported fields
}

Snapshot provides a consistent view of read operations in a DB.

func NewNativeSnapshot Uses

func NewNativeSnapshot(c *C.rocksdb_snapshot_t) *Snapshot

NewNativeSnapshot creates a Snapshot object.

type Transaction Uses

type Transaction struct {
    // contains filtered or unexported fields
}

Transaction is used with TransactionDB for transaction support.

func NewNativeTransaction Uses

func NewNativeTransaction(c *C.rocksdb_transaction_t) *Transaction

NewNativeTransaction creates a Transaction object.

func (*Transaction) Commit Uses

func (transaction *Transaction) Commit() error

Commit commits the transaction to the database.

func (*Transaction) Delete Uses

func (transaction *Transaction) Delete(key []byte) error

Delete removes the data associated with the key from the transaction.

func (*Transaction) Destroy Uses

func (transaction *Transaction) Destroy()

Destroy deallocates the transaction object.

func (*Transaction) Get Uses

func (transaction *Transaction) Get(opts *ReadOptions, key []byte) (*Slice, error)

Get returns the data associated with the key from the database given this transaction.

func (*Transaction) GetForUpdate Uses

func (transaction *Transaction) GetForUpdate(opts *ReadOptions, key []byte) (*Slice, error)

GetForUpdate queries the data associated with the key and puts an exclusive lock on the key from the database given this transaction.

func (*Transaction) NewIterator Uses

func (transaction *Transaction) NewIterator(opts *ReadOptions) *Iterator

NewIterator returns an Iterator over the database that uses the ReadOptions given.

func (*Transaction) Put Uses

func (transaction *Transaction) Put(key, value []byte) error

Put writes data associated with a key to the transaction.

func (*Transaction) Rollback Uses

func (transaction *Transaction) Rollback() error

Rollback performs a rollback on the transaction.

type TransactionDB Uses

type TransactionDB struct {
    // contains filtered or unexported fields
}

TransactionDB is a reusable handle to a RocksDB transactional database on disk, created by OpenTransactionDb.

func OpenTransactionDb Uses

func OpenTransactionDb(
    opts *Options,
    transactionDBOpts *TransactionDBOptions,
    name string,
) (*TransactionDB, error)

OpenTransactionDb opens a database with the specified options.

func (*TransactionDB) Close Uses

func (transactionDB *TransactionDB) Close()

Close closes the database.

func (*TransactionDB) Delete Uses

func (db *TransactionDB) Delete(opts *WriteOptions, key []byte) error

Delete removes the data associated with the key from the database.

func (*TransactionDB) Get Uses

func (db *TransactionDB) Get(opts *ReadOptions, key []byte) (*Slice, error)

Get returns the data associated with the key from the database.

func (*TransactionDB) NewCheckpoint Uses

func (db *TransactionDB) NewCheckpoint() (*Checkpoint, error)

NewCheckpoint creates a new Checkpoint for this db.

func (*TransactionDB) NewSnapshot Uses

func (db *TransactionDB) NewSnapshot() *Snapshot

NewSnapshot creates a new snapshot of the database.

func (*TransactionDB) Put Uses

func (db *TransactionDB) Put(opts *WriteOptions, key, value []byte) error

Put writes data associated with a key to the database.

func (*TransactionDB) ReleaseSnapshot Uses

func (db *TransactionDB) ReleaseSnapshot(snapshot *Snapshot)

ReleaseSnapshot releases the snapshot and its resources.

func (*TransactionDB) TransactionBegin Uses

func (db *TransactionDB) TransactionBegin(
    opts *WriteOptions,
    transactionOpts *TransactionOptions,
    oldTransaction *Transaction,
) *Transaction

TransactionBegin begins a new transaction with the WriteOptions and TransactionOptions given.

type TransactionDBOptions Uses

type TransactionDBOptions struct {
    // contains filtered or unexported fields
}

TransactionDBOptions represent all of the available options when opening a transactional database with OpenTransactionDb.

func NewDefaultTransactionDBOptions Uses

func NewDefaultTransactionDBOptions() *TransactionDBOptions

NewDefaultTransactionDBOptions creates a default TransactionDBOptions object.

func NewNativeTransactionDBOptions Uses

func NewNativeTransactionDBOptions(c *C.rocksdb_transactiondb_options_t) *TransactionDBOptions

NewDefaultTransactionDBOptions creates a TransactionDBOptions object.

func (*TransactionDBOptions) Destroy Uses

func (opts *TransactionDBOptions) Destroy()

Destroy deallocates the TransactionDBOptions object.

func (*TransactionDBOptions) SetDefaultLockTimeout Uses

func (opts *TransactionDBOptions) SetDefaultLockTimeout(default_lock_timeout int64)

SetDefaultLockTimeout if posititve, specifies the wait timeout in milliseconds when writing a key OUTSIDE of a transaction (ie by calling DB::Put(),Merge(),Delete(),Write() directly). If 0, no waiting is done if a lock cannot instantly be acquired. If negative, there is no timeout and will block indefinitely when acquiring a lock.

Not using a timeout can lead to deadlocks. Currently, there is no deadlock-detection to recover from a deadlock. While DB writes cannot deadlock with other DB writes, they can deadlock with a transaction. A negative timeout should only be used if all transactions have a small expiration set.

func (*TransactionDBOptions) SetMaxNumLocks Uses

func (opts *TransactionDBOptions) SetMaxNumLocks(max_num_locks int64)

SetMaxNumLocks sets the maximum number of keys that can be locked at the same time per column family. If the number of locked keys is greater than max_num_locks, transaction writes (or GetForUpdate) will return an error. If this value is not positive, no limit will be enforced.

func (*TransactionDBOptions) SetNumStripes Uses

func (opts *TransactionDBOptions) SetNumStripes(num_stripes uint64)

SetNumStripes sets the concurrency level. Increasing this value will increase the concurrency by dividing the lock table (per column family) into more sub-tables, each with their own separate mutex.

func (*TransactionDBOptions) SetTransactionLockTimeout Uses

func (opts *TransactionDBOptions) SetTransactionLockTimeout(txn_lock_timeout int64)

SetTransactionLockTimeout if positive, specifies the default wait timeout in milliseconds when a transaction attempts to lock a key if not specified by TransactionOptions::lock_timeout.

If 0, no waiting is done if a lock cannot instantly be acquired. If negative, there is no timeout. Not using a timeout is not recommended as it can lead to deadlocks. Currently, there is no deadlock-detection to recover from a deadlock.

type TransactionOptions Uses

type TransactionOptions struct {
    // contains filtered or unexported fields
}

TransactionOptions represent all of the available options options for a transaction on the database.

func NewDefaultTransactionOptions Uses

func NewDefaultTransactionOptions() *TransactionOptions

NewDefaultTransactionOptions creates a default TransactionOptions object.

func NewNativeTransactionOptions Uses

func NewNativeTransactionOptions(c *C.rocksdb_transaction_options_t) *TransactionOptions

NewNativeTransactionOptions creates a TransactionOptions object.

func (*TransactionOptions) Destroy Uses

func (opts *TransactionOptions) Destroy()

Destroy deallocates the TransactionOptions object.

func (*TransactionOptions) SetDeadlockDetect Uses

func (opts *TransactionOptions) SetDeadlockDetect(value bool)

SetDeadlockDetect to true means that before acquiring locks, this transaction will check if doing so will cause a deadlock. If so, it will return with Status::Busy. The user should retry their transaction.

func (*TransactionOptions) SetDeadlockDetectDepth Uses

func (opts *TransactionOptions) SetDeadlockDetectDepth(depth int64)

SetDeadlockDetectDepth sets the number of traversals to make during deadlock detection.

func (*TransactionOptions) SetExpiration Uses

func (opts *TransactionOptions) SetExpiration(expiration int64)

SetExpiration sets the Expiration duration in milliseconds. If non-negative, transactions that last longer than this many milliseconds will fail to commit. If not set, a forgotten transaction that is never committed, rolled back, or deleted will never relinquish any locks it holds. This could prevent keys from being written by other writers.

func (*TransactionOptions) SetLockTimeout Uses

func (opts *TransactionOptions) SetLockTimeout(lock_timeout int64)

SetLockTimeout positive, specifies the wait timeout in milliseconds when a transaction attempts to lock a key. If 0, no waiting is done if a lock cannot instantly be acquired. If negative, TransactionDBOptions::transaction_lock_timeout will be used

func (*TransactionOptions) SetMaxWriteBatchSize Uses

func (opts *TransactionOptions) SetMaxWriteBatchSize(size uint64)

SetMaxWriteBatchSize sets the maximum number of bytes used for the write batch. 0 means no limit.

func (*TransactionOptions) SetSetSnapshot Uses

func (opts *TransactionOptions) SetSetSnapshot(value bool)

SetSetSnapshot to true is the same as calling Transaction::SetSnapshot().

type UniversalCompactionOptions Uses

type UniversalCompactionOptions struct {
    // contains filtered or unexported fields
}

UniversalCompactionOptions represent all of the available options for universal compaction.

func NewDefaultUniversalCompactionOptions Uses

func NewDefaultUniversalCompactionOptions() *UniversalCompactionOptions

NewDefaultUniversalCompactionOptions creates a default UniversalCompactionOptions object.

func NewNativeUniversalCompactionOptions Uses

func NewNativeUniversalCompactionOptions(c *C.rocksdb_universal_compaction_options_t) *UniversalCompactionOptions

NewNativeUniversalCompactionOptions creates a UniversalCompactionOptions object.

func (*UniversalCompactionOptions) Destroy Uses

func (opts *UniversalCompactionOptions) Destroy()

Destroy deallocates the UniversalCompactionOptions object.

func (*UniversalCompactionOptions) SetCompressionSizePercent Uses

func (opts *UniversalCompactionOptions) SetCompressionSizePercent(value int)

SetCompressionSizePercent sets the percentage of compression size.

If this option is set to be -1, all the output files will follow compression type specified.

If this option is not negative, we will try to make sure compressed size is just above this value. In normal cases, at least this percentage of data will be compressed. When we are compacting to a new file, here is the criteria whether it needs to be compressed: assuming here are the list of files sorted by generation time:

A1...An B1...Bm C1...Ct

where A1 is the newest and Ct is the oldest, and we are going to compact B1...Bm, we calculate the total size of all the files as total_size, as well as the total size of C1...Ct as total_C, the compaction output file will be compressed iff

total_C / total_size < this percentage

Default: -1

func (*UniversalCompactionOptions) SetMaxMergeWidth Uses

func (opts *UniversalCompactionOptions) SetMaxMergeWidth(value uint)

SetMaxMergeWidth sets the maximum number of files in a single compaction run. Default: UINT_MAX

func (*UniversalCompactionOptions) SetMaxSizeAmplificationPercent Uses

func (opts *UniversalCompactionOptions) SetMaxSizeAmplificationPercent(value uint)

SetMaxSizeAmplificationPercent sets the size amplification. It is defined as the amount (in percentage) of additional storage needed to store a single byte of data in the database. For example, a size amplification of 2% means that a database that contains 100 bytes of user-data may occupy upto 102 bytes of physical storage. By this definition, a fully compacted database has a size amplification of 0%. Rocksdb uses the following heuristic to calculate size amplification: it assumes that all files excluding the earliest file contribute to the size amplification. Default: 200, which means that a 100 byte database could require upto 300 bytes of storage.

func (*UniversalCompactionOptions) SetMinMergeWidth Uses

func (opts *UniversalCompactionOptions) SetMinMergeWidth(value uint)

SetMinMergeWidth sets the minimum number of files in a single compaction run. Default: 2

func (*UniversalCompactionOptions) SetSizeRatio Uses

func (opts *UniversalCompactionOptions) SetSizeRatio(value uint)

SetSizeRatio sets the percentage flexibilty while comparing file size. If the candidate file(s) size is 1% smaller than the next file's size, then include next file into this candidate set. Default: 1

func (*UniversalCompactionOptions) SetStopStyle Uses

func (opts *UniversalCompactionOptions) SetStopStyle(value UniversalCompactionStopStyle)

SetStopStyle sets the algorithm used to stop picking files into a single compaction run. Default: CompactionStopStyleTotalSize

type UniversalCompactionStopStyle Uses

type UniversalCompactionStopStyle uint

UniversalCompactionStopStyle describes a algorithm used to make a compaction request stop picking new files into a single compaction run.

type WALRecoveryMode Uses

type WALRecoveryMode int

type WalIterator Uses

type WalIterator struct {
    // contains filtered or unexported fields
}

func NewNativeWalIterator Uses

func NewNativeWalIterator(c unsafe.Pointer) *WalIterator

func (*WalIterator) Destroy Uses

func (iter *WalIterator) Destroy()

func (*WalIterator) Err Uses

func (iter *WalIterator) Err() error

func (*WalIterator) GetBatch Uses

func (iter *WalIterator) GetBatch() (*WriteBatch, uint64)

C.rocksdb_wal_iter_get_batch in the official rocksdb c wrapper has memory leak see https://github.com/facebook/rocksdb/pull/5515

https://github.com/facebook/rocksdb/issues/5536

func (*WalIterator) Next Uses

func (iter *WalIterator) Next()

func (*WalIterator) Valid Uses

func (iter *WalIterator) Valid() bool

type WriteBatch Uses

type WriteBatch struct {
    // contains filtered or unexported fields
}

WriteBatch is a batching of Puts, Merges and Deletes.

func NewNativeWriteBatch Uses

func NewNativeWriteBatch(c *C.rocksdb_writebatch_t) *WriteBatch

NewNativeWriteBatch create a WriteBatch object.

func NewWriteBatch Uses

func NewWriteBatch() *WriteBatch

NewWriteBatch create a WriteBatch object.

func WriteBatchFrom Uses

func WriteBatchFrom(data []byte) *WriteBatch

WriteBatchFrom creates a write batch from a serialized WriteBatch.

func (*WriteBatch) Clear Uses

func (wb *WriteBatch) Clear()

Clear removes all the enqueued Put and Deletes.

func (*WriteBatch) Count Uses

func (wb *WriteBatch) Count() int

Count returns the number of updates in the batch.

func (*WriteBatch) Data Uses

func (wb *WriteBatch) Data() []byte

Data returns the serialized version of this batch.

func (*WriteBatch) Delete Uses

func (wb *WriteBatch) Delete(key []byte)

Delete queues a deletion of the data at key.

func (*WriteBatch) DeleteCF Uses

func (wb *WriteBatch) DeleteCF(cf *ColumnFamilyHandle, key []byte)

DeleteCF queues a deletion of the data at key in a column family.

func (*WriteBatch) DeleteRange Uses

func (wb *WriteBatch) DeleteRange(startKey []byte, endKey []byte)

DeleteRange deletes keys that are between [startKey, endKey)

func (*WriteBatch) DeleteRangeCF Uses

func (wb *WriteBatch) DeleteRangeCF(cf *ColumnFamilyHandle, startKey []byte, endKey []byte)

DeleteRangeCF deletes keys that are between [startKey, endKey) and belong to a given column family

func (*WriteBatch) Destroy Uses

func (wb *WriteBatch) Destroy()

Destroy deallocates the WriteBatch object.

func (*WriteBatch) Merge Uses

func (wb *WriteBatch) Merge(key, value []byte)

Merge queues a merge of "value" with the existing value of "key".

func (*WriteBatch) MergeCF Uses

func (wb *WriteBatch) MergeCF(cf *ColumnFamilyHandle, key, value []byte)

MergeCF queues a merge of "value" with the existing value of "key" in a column family.

func (*WriteBatch) NewIterator Uses

func (wb *WriteBatch) NewIterator() *WriteBatchIterator

NewIterator returns a iterator to iterate over the records in the batch.

func (*WriteBatch) Put Uses

func (wb *WriteBatch) Put(key, value []byte)

Put queues a key-value pair.

func (*WriteBatch) PutCF Uses

func (wb *WriteBatch) PutCF(cf *ColumnFamilyHandle, key, value []byte)

PutCF queues a key-value pair in a column family.

func (*WriteBatch) PutLogData Uses

func (wb *WriteBatch) PutLogData(blob []byte)

Append a blob of arbitrary size to the records in this batch.

type WriteBatchIterator Uses

type WriteBatchIterator struct {
    // contains filtered or unexported fields
}

WriteBatchIterator represents a iterator to iterator over records.

func (*WriteBatchIterator) Error Uses

func (iter *WriteBatchIterator) Error() error

Error returns the error if the iteration is failed.

func (*WriteBatchIterator) Next Uses

func (iter *WriteBatchIterator) Next() bool

Next returns the next record. Returns false if no further record exists.

func (*WriteBatchIterator) Record Uses

func (iter *WriteBatchIterator) Record() *WriteBatchRecord

Record returns the current record.

type WriteBatchRecord Uses

type WriteBatchRecord struct {
    CF    int
    Key   []byte
    Value []byte
    Type  WriteBatchRecordType
}

WriteBatchRecord represents a record inside a WriteBatch.

type WriteBatchRecordType Uses

type WriteBatchRecordType byte

WriteBatchRecordType describes the type of a batch record.

const (
    WriteBatchDeletionRecord                 WriteBatchRecordType = 0x0
    WriteBatchValueRecord                    WriteBatchRecordType = 0x1
    WriteBatchMergeRecord                    WriteBatchRecordType = 0x2
    WriteBatchLogDataRecord                  WriteBatchRecordType = 0x3
    WriteBatchCFDeletionRecord               WriteBatchRecordType = 0x4
    WriteBatchCFValueRecord                  WriteBatchRecordType = 0x5
    WriteBatchCFMergeRecord                  WriteBatchRecordType = 0x6
    WriteBatchSingleDeletionRecord           WriteBatchRecordType = 0x7
    WriteBatchCFSingleDeletionRecord         WriteBatchRecordType = 0x8
    WriteBatchBeginPrepareXIDRecord          WriteBatchRecordType = 0x9
    WriteBatchEndPrepareXIDRecord            WriteBatchRecordType = 0xA
    WriteBatchCommitXIDRecord                WriteBatchRecordType = 0xB
    WriteBatchRollbackXIDRecord              WriteBatchRecordType = 0xC
    WriteBatchNoopRecord                     WriteBatchRecordType = 0xD
    WriteBatchRangeDeletion                  WriteBatchRecordType = 0xF
    WriteBatchCFRangeDeletion                WriteBatchRecordType = 0xE
    WriteBatchCFBlobIndex                    WriteBatchRecordType = 0x10
    WriteBatchBlobIndex                      WriteBatchRecordType = 0x11
    WriteBatchBeginPersistedPrepareXIDRecord WriteBatchRecordType = 0x12
    WriteBatchNotUsedRecord                  WriteBatchRecordType = 0x7F
)

Types of batch records.

type WriteOptions Uses

type WriteOptions struct {
    // contains filtered or unexported fields
}

WriteOptions represent all of the available options when writing to a database.

func NewDefaultWriteOptions Uses

func NewDefaultWriteOptions() *WriteOptions

NewDefaultWriteOptions creates a default WriteOptions object.

func NewNativeWriteOptions Uses

func NewNativeWriteOptions(c *C.rocksdb_writeoptions_t) *WriteOptions

NewNativeWriteOptions creates a WriteOptions object.

func (*WriteOptions) Destroy Uses

func (opts *WriteOptions) Destroy()

Destroy deallocates the WriteOptions object.

func (*WriteOptions) DisableWAL Uses

func (opts *WriteOptions) DisableWAL(value bool)

DisableWAL sets whether WAL should be active or not. If true, writes will not first go to the write ahead log, and the write may got lost after a crash. Default: false

func (*WriteOptions) SetSync Uses

func (opts *WriteOptions) SetSync(value bool)

SetSync sets the sync mode. If true, the write will be flushed from the operating system buffer cache before the write is considered complete. If this flag is true, writes will be slower. Default: false

Package gorocksdb imports 9 packages (graph) and is imported by 267 packages. Updated 2019-12-18. Refresh now. Tools for package owners.