How does LevelDB seek through compressed keys?
Write six keys to a real SSTable. Follow restart offsets 0 and 30 to see how Seek finds a successor when there is no exact match.
Start with six keys on disk
Google’s LevelDB is an embedded ordered key-value store. Imagine a local index containing car, cart, cat, dog, dot, dove. Seeking caz should land on dog, the first key greater than or equal to the target. The complication is that the disk block omits prefixes shared with the previous key. Decoding at an arbitrary record would require information from its predecessor.
Google’s official repository · LevelDB 1.23 · BSD-3-Clause license
How the writer makes seeking possible
Open BlockBuilder::Add. Storing cart after car takes a shared length of 3 and the suffix t. We set the restart interval to 3. At the fourth key, dog, the writer resets the shared length to zero and writes an independently decodable key. Finish appends the restart offsets and their count to the block. Read the block writer.
Now open Block::Iter::Seek. For caz, binary search over full restart keys selects the group beginning at car. After reconstructing car, cart, cat, the first qualifying record is dog at the next restart. A second seek for zzz reaches the end. This example uses TableBuilder to write a table and Table::Open to reopen it, exercising the on-disk table read path. Read the binary search and forward decoding loop.
With R restart points and restart interval K, a fresh seek within one block takes O(log R + K) key comparisons or decodes when each key operation is counted as a unit. Key length, table indexes, caching and disk I/O also affect end-to-end database latency.
Build and run locally
Use a fresh directory on macOS or Linux with curl, tar, CMake, a C/C++ toolchain supporting C++17, and POSIX threads. These commands build a static library with tests, benchmarks and optional compression dependencies disabled. The example writes example.ldb in the working directory. We ran it on Apple Silicon macOS.
Download the complete C++17 example · Build commands as plain text
Read the example source
#include <iostream>
#include <memory>
#include <stdexcept>
#include <string>
#include "leveldb/env.h"
#include "leveldb/iterator.h"
#include "leveldb/table.h"
#include "leveldb/table_builder.h"
void check(const leveldb::Status& status) {
if (!status.ok()) {
throw std::runtime_error(status.ToString());
}
}
int main() {
const char* path = "example.ldb";
leveldb::Options options;
options.block_restart_interval = 3;
options.compression = leveldb::kNoCompression;
auto* env = leveldb::Env::Default();
leveldb::WritableFile* raw_output = nullptr;
check(env->NewWritableFile(path, &raw_output));
std::unique_ptr<leveldb::WritableFile> output(raw_output);
leveldb::TableBuilder builder(options, output.get());
for (const char* key : {"car", "cart", "cat", "dog", "dot", "dove"}) {
builder.Add(key, std::string("v_") + key);
}
check(builder.Finish());
check(output->Close());
uint64_t size = 0;
check(env->GetFileSize(path, &size));
leveldb::RandomAccessFile* raw_input = nullptr;
check(env->NewRandomAccessFile(path, &raw_input));
std::unique_ptr<leveldb::RandomAccessFile> input(raw_input);
leveldb::Table* raw_table = nullptr;
check(leveldb::Table::Open(options, input.get(), size, &raw_table));
std::unique_ptr<leveldb::Table> table(raw_table);
std::unique_ptr<leveldb::Iterator> iter(
table->NewIterator(leveldb::ReadOptions{}));
iter->Seek("caz");
check(iter->status());
if (!iter->Valid() || iter->key().ToString() != "dog" ||
iter->value().ToString() != "v_dog") {
return 1;
}
std::cout << "Seek(caz) = " << iter->key().ToString() << " -> "
<< iter->value().ToString() << '\n';
iter->Seek("zzz");
check(iter->status());
if (iter->Valid()) {
return 1;
}
std::cout << "Seek(zzz) = <end>\n";
}mkdir leveldb-study && cd leveldb-study
curl -fsSL https://codeload.github.com/google/leveldb/tar.gz/refs/tags/1.23 -o leveldb.tgz
tar -xzf leveldb.tgz
curl -fsSLO https://www.juyaoai.com/examples/leveldb-block-seek/demo.cpp
cmake -S leveldb-1.23 -B build -DCMAKE_BUILD_TYPE=Release \
-DCMAKE_POLICY_VERSION_MINIMUM=3.5 -DBUILD_SHARED_LIBS=OFF \
-DLEVELDB_BUILD_TESTS=OFF -DLEVELDB_BUILD_BENCHMARKS=OFF \
-DLEVELDB_INSTALL=OFF -DHAVE_SNAPPY=OFF -DHAVE_CRC32C=OFF
cmake --build build --target leveldb --parallel 4
c++ -std=c++17 -Wall -Wextra -pedantic -I leveldb-1.23/include \
demo.cpp build/libleveldb.a -pthread -o demo
./demoResults and a follow-up experiment
Seek(caz) = dog -> v_dog
Seek(zzz) = <end>
Change the restart interval to 1 to make every key independently decodable. Then set it to 6 so that only the first key restarts decoding. Both lookups should give the same answers. Run wc -c example.ldb after each build of the example and inspect the number of decoded records in Block::Iter::Seek. The file is 158 bytes with the interval set to 3.