Skip to main content

Overview

The DB class is the primary interface for interacting with a RocksDB database. It provides methods for reading, writing, and managing a persistent, versioned ordered map from keys to values. The DB is safe for concurrent access from multiple threads without any external synchronization.

Opening a Database

Open

Open the database with the specified name for reads and writes.
static Status Open(const Options& options, 
                   const std::string& name,
                   std::unique_ptr<DB>* dbptr);
options
const Options&
Database configuration options
name
const std::string&
Path to the database directory
dbptr
std::unique_ptr<DB>*
Output parameter that will store the database instance on success
Status
Status
Returns OK on success, or a non-OK status on error (including if the DB is already open read-write by another DB object)
Options options;
options.create_if_missing = true;

std::unique_ptr<DB> db;
Status s = DB::Open(options, "/path/to/db", &db);
if (s.ok()) {
  // Database opened successfully
}

Open with Column Families

Open database with column families support.
static Status Open(const DBOptions& db_options,
                   const std::string& name,
                   const std::vector<ColumnFamilyDescriptor>& column_families,
                   std::vector<ColumnFamilyHandle*>* handles,
                   std::unique_ptr<DB>* dbptr);
db_options
const DBOptions&
Database-level options
name
const std::string&
Path to the database directory
column_families
const std::vector<ColumnFamilyDescriptor>&
Vector of all column families in the database. You need to open ALL column families.
handles
std::vector<ColumnFamilyHandle*>*
Output vector of column family handles (will be same size as column_families)
dbptr
std::unique_ptr<DB>*
Output parameter for the database instance
DBOptions db_options;
std::vector<ColumnFamilyDescriptor> column_families;
column_families.push_back(ColumnFamilyDescriptor(
    kDefaultColumnFamilyName, ColumnFamilyOptions()));
column_families.push_back(ColumnFamilyDescriptor(
    "new_cf", ColumnFamilyOptions()));

std::vector<ColumnFamilyHandle*> handles;
std::unique_ptr<DB> db;
Status s = DB::Open(db_options, "/path/to/db", 
                    column_families, &handles, &db);

OpenForReadOnly

Create a read-only instance that supports reads alone.
static Status OpenForReadOnly(const Options& options,
                              const std::string& name,
                              std::unique_ptr<DB>* dbptr,
                              bool error_if_wal_file_exists = false);
error_if_wal_file_exists
bool
default:"false"
If true, returns error when WAL files exist
All DB interfaces that modify data (Put/Delete) will return error. Automatic Flush and Compactions are disabled.

OpenAsSecondary

Create a secondary instance that supports read-only operations with dynamic catch-up.
static Status OpenAsSecondary(const Options& options,
                              const std::string& name,
                              const std::string& secondary_path,
                              std::unique_ptr<DB>* dbptr);
secondary_path
const std::string&
Directory where the secondary instance stores its info log
Options.max_open_files should be set to -1 for secondary instances.

Write Operations

Put

Set the database entry for “key” to “value”.
virtual Status Put(const WriteOptions& options,
                   ColumnFamilyHandle* column_family,
                   const Slice& key,
                   const Slice& value) = 0;

virtual Status Put(const WriteOptions& options,
                   const Slice& key,
                   const Slice& value);
options
const WriteOptions&
Write options (e.g., sync behavior)
column_family
ColumnFamilyHandle*
Target column family (default column family if not specified)
key
const Slice&
The key to set
value
const Slice&
The value to store
If “key” already exists, it will be overwritten. Consider setting options.sync = true.
WriteOptions write_options;
write_options.sync = true;

Status s = db->Put(write_options, "key1", "value1");
if (!s.ok()) {
  // Handle error
}

Delete

Remove the database entry for “key”.
virtual Status Delete(const WriteOptions& options,
                      ColumnFamilyHandle* column_family,
                      const Slice& key) = 0;

virtual Status Delete(const WriteOptions& options,
                      const Slice& key);
Status
Status
Returns OK on success. It is not an error if “key” did not exist in the database.

DeleteRange

Remove database entries in the range [begin_key, end_key).
virtual Status DeleteRange(const WriteOptions& options,
                           ColumnFamilyHandle* column_family,
                           const Slice& begin_key,
                           const Slice& end_key);
begin_key
const Slice&
Start of the range (inclusive)
end_key
const Slice&
End of the range (exclusive)
If “end_key” comes before “begin_key” according to the comparator, Status::InvalidArgument is returned.
This feature is production-ready with these caveats:
  1. Accumulating too many range tombstones in the memtable will degrade read performance
  2. Limiting max_open_files with range tombstones can degrade read performance (set to -1 when possible)
  3. Incompatible with row_cache

Merge

Merge the database entry for “key” with “value”.
virtual Status Merge(const WriteOptions& options,
                     ColumnFamilyHandle* column_family,
                     const Slice& key,
                     const Slice& value) = 0;
The semantics of this operation is determined by the user-provided merge_operator when opening the DB.

Write

Apply the specified updates atomically to the database.
virtual Status Write(const WriteOptions& options, 
                     WriteBatch* updates) = 0;
updates
WriteBatch*
Batch of write operations to apply atomically
If updates contains no update, WAL will still be synced if options.sync=true.

Read Operations

Get

Retrieve the value for a given key.
virtual Status Get(const ReadOptions& options,
                   ColumnFamilyHandle* column_family,
                   const Slice& key,
                   PinnableSlice* value,
                   std::string* timestamp) = 0;

virtual Status Get(const ReadOptions& options,
                   const Slice& key,
                   std::string* value);
options
const ReadOptions&
Read options (e.g., snapshot, verify_checksums)
key
const Slice&
The key to retrieve
value
PinnableSlice*
Output parameter for the retrieved value
timestamp
std::string*
Optional output parameter for timestamp (if enabled)
Status
Status
Returns OK on success, NotFound if there is no entry for “key”, or other non-OK status on error
ReadOptions read_options;
std::string value;
Status s = db->Get(read_options, "key1", &value);
if (s.ok()) {
  // Use value
} else if (s.IsNotFound()) {
  // Key not found
}

MultiGet

Batched key retrieval for better performance.
virtual void MultiGet(const ReadOptions& options,
                      const size_t num_keys,
                      ColumnFamilyHandle** column_families,
                      const Slice* keys,
                      PinnableSlice* values,
                      std::string* timestamps,
                      Status* statuses,
                      const bool sorted_input = false) = 0;
num_keys
size_t
Number of keys to lookup
column_families
ColumnFamilyHandle**
Array of column family handles for each key
keys
const Slice*
Array of keys to retrieve
values
PinnableSlice*
Array for output values
statuses
Status*
Array for per-key status results
sorted_input
bool
default:"false"
Set true if keys are already sorted by key order (optimization)
This API improves performance by batching operations in the read path. Currently optimized for block based table format with full filters.

NewIterator

Create an iterator over the database contents.
virtual Iterator* NewIterator(const ReadOptions& options,
                              ColumnFamilyHandle* column_family) = 0;

virtual Iterator* NewIterator(const ReadOptions& options);
Iterator*
Iterator*
Heap-allocated iterator (caller must delete). Initially invalid - must call Seek before using.
ReadOptions read_options;
Iterator* it = db->NewIterator(read_options);
for (it->SeekToFirst(); it->Valid(); it->Next()) {
  std::cout << it->key().ToString() << ": " 
            << it->value().ToString() << std::endl;
}
delete it;

Column Family Management

CreateColumnFamily

Create a new column family.
virtual Status CreateColumnFamily(const ColumnFamilyOptions& options,
                                  const std::string& column_family_name,
                                  ColumnFamilyHandle** handle);
Creating many column families one-by-one is not recommended due to quadratic overheads. Use CreateColumnFamilies() or DB::Open() with create_missing_column_families=true instead.

DropColumnFamily

Drop a column family.
virtual Status DropColumnFamily(ColumnFamilyHandle* column_family);
This call only records a drop record in the manifest and prevents the column family from flushing and compacting.

DestroyColumnFamilyHandle

Release and deallocate a column family handle.
virtual Status DestroyColumnFamilyHandle(ColumnFamilyHandle* column_family);
A column family is only removed once it is dropped AND all handles have been destroyed. Use this method to destroy handles before closing the DB.

ListColumnFamilies

Get the list of all column families in a database.
static Status ListColumnFamilies(const DBOptions& db_options,
                                 const std::string& name,
                                 std::vector<std::string>* column_families);

Database Management

Close

Close the database by releasing resources.
virtual Status Close();
This should be called before the destructor. Does not fsync WAL files - call SyncWAL() first if needed. The DB must be freed regardless of return status.

CompactRange

Manually compact a key range.
virtual Status CompactRange(const CompactRangeOptions& options,
                            ColumnFamilyHandle* column_family,
                            const Slice* begin,
                            const Slice* end) = 0;
begin
const Slice*
Start of range (nullptr = before all keys)
end
const Slice*
End of range (nullptr = after all keys)
This call blocks until the operation completes, fails, or is aborted (Status::Incomplete).

Flush

Flush all memtable data to SST files.
virtual Status Flush(const FlushOptions& options,
                     ColumnFamilyHandle* column_family) = 0;

GetSnapshot

Create a snapshot of the current DB state.
virtual const Snapshot* GetSnapshot() = 0;
Snapshot*
const Snapshot*
Snapshot handle. Returns nullptr if the DB fails to take a snapshot or does not support snapshots.

ReleaseSnapshot

Release a previously acquired snapshot.
virtual void ReleaseSnapshot(const Snapshot* snapshot) = 0;
The caller must not use “snapshot” after this call.

Properties and Statistics

GetProperty

Get database property values.
virtual bool GetProperty(ColumnFamilyHandle* column_family,
                         const Slice& property,
                         std::string* value) = 0;
std::string value;
if (db->GetProperty("rocksdb.num-files-at-level0", &value)) {
  std::cout << "L0 files: " << value << std::endl;
}

GetIntProperty

Get integer property values.
virtual bool GetIntProperty(ColumnFamilyHandle* column_family,
                            const Slice& property,
                            uint64_t* value) = 0;
Supported properties include: “rocksdb.num-immutable-mem-table”, “rocksdb.estimate-num-keys”, “rocksdb.total-sst-files-size”, and many more.

Build docs developers (and LLMs) love