Overview
This guide will walk you through creating your first RocksDB application. You’ll learn how to open a database, perform basic operations, and understand core concepts.This guide assumes you have already installed RocksDB on your system.
Your First RocksDB Program
Let’s build a simple program that demonstrates the basic CRUD operations in RocksDB.1
Include Required Headers
Start by including the necessary RocksDB headers:Import the RocksDB namespace:
2
Configure and Open the Database
Configure your database options and open it:
Performance Tip:
IncreaseParallelism() sets the number of background threads to the number of CPU cores, and OptimizeLevelStyleCompaction() configures options optimized for level-style compaction.3
Write Data (Put)
Store a key-value pair:The
Put() method takes:WriteOptions- Controls write behavior (sync, disable WAL, etc.)key- The key as a string or Slicevalue- The value to store
4
Read Data (Get)
Retrieve a value by key:The
Get() method returns:Status::OK()if the key existsStatus::NotFound()if the key doesn’t exist- Other error statuses for failures
5
Atomic Batch Operations
Apply multiple operations atomically using WriteBatch:
6
Delete Data
Remove a key from the database:
Complete Example
Here’s the complete working example from the RocksDB source code:examples/simple_example.cc
Using PinnableSlice for Better Performance
For better performance, usePinnableSlice instead of std::string to avoid unnecessary memory copies:
Performance Optimization:
PinnableSlice can avoid a memcpy by directly pointing to RocksDB’s internal buffer when possible. Always call Reset() before reusing a PinnableSlice.PinnableSlice with Fallback Buffer
Compiling Your Program
RocksDB requires C++20 support. Ensure you have GCC 11+ or Clang 10+ installed.
Understanding Status Objects
RocksDB usesStatus objects to indicate success or failure:
Common Status Methods
bool
Returns true if the operation succeeded
bool
Returns true if the key was not found
bool
Returns true if data corruption was detected
bool
Returns true if an I/O error occurred
std::string
Returns a human-readable error message
Important Options
Database Options
Write Options
Read Options
Next Steps
Column Families
Learn how to partition your data logically
Transactions
Implement ACID transactions
Iterators
Scan ranges of keys efficiently
Backup & Restore
Protect your data with backups