Skip to main content
This guide covers the fundamental Create, Read, Update, and Delete (CRUD) operations in RocksDB.

Opening a Database

Before performing any operations, you need to open a RocksDB database:
The IncreaseParallelism() and OptimizeLevelStyleCompaction() methods are the easiest way to get good performance from RocksDB. They set reasonable defaults for most workloads.

Write Operations

Put - Writing Key-Value Pairs

The Put operation writes or updates a key-value pair:
Example:
If the key already exists, Put will overwrite the existing value.

Delete - Removing Keys

The Delete operation removes a key from the database:
Example:

Read Operations

Get - Reading Values

The Get operation retrieves the value associated with a key:
Example:

Using PinnableSlice for Better Performance

For better performance, use PinnableSlice to avoid unnecessary memory copies:
Always call Reset() on a PinnableSlice before reusing it. The Slice pointed by pinnable_val is not valid after calling Reset().

Atomic Batch Operations

RocksDB allows you to apply multiple operations atomically using WriteBatch:
After the batch is applied:
1

Create a WriteBatch

Instantiate a WriteBatch object to hold multiple operations.
2

Add operations

Add Put, Delete, or other operations to the batch.
3

Apply atomically

Call db->Write() to apply all operations atomically.

Error Handling

All RocksDB operations return a Status object that indicates success or failure:

Closing the Database

RocksDB databases are automatically closed when the DB object is destroyed:

Complete Example

Here’s a complete example demonstrating basic operations:

Next Steps

Configuration

Learn how to configure RocksDB for your workload

Iterators

Learn how to scan and iterate through data

Transactions

Implement ACID transactions for your application

Merge Operators

Implement read-modify-write semantics efficiently