1leveldb 2======= 3 4_Jeff Dean, Sanjay Ghemawat_ 5 6The leveldb library provides a persistent key value store. Keys and values are 7arbitrary byte arrays. The keys are ordered within the key value store 8according to a user-specified comparator function. 9 10## Opening A Database 11 12A leveldb database has a name which corresponds to a file system directory. All 13of the contents of database are stored in this directory. The following example 14shows how to open a database, creating it if necessary: 15 16```c++ 17#include <cassert> 18#include "leveldb/db.h" 19 20leveldb::DB* db; 21leveldb::Options options; 22options.create_if_missing = true; 23leveldb::Status status = leveldb::DB::Open(options, "/tmp/testdb", &db); 24assert(status.ok()); 25... 26``` 27 28If you want to raise an error if the database already exists, add the following 29line before the `leveldb::DB::Open` call: 30 31```c++ 32options.error_if_exists = true; 33``` 34 35## Status 36 37You may have noticed the `leveldb::Status` type above. Values of this type are 38returned by most functions in leveldb that may encounter an error. You can check 39if such a result is ok, and also print an associated error message: 40 41```c++ 42leveldb::Status s = ...; 43if (!s.ok()) cerr << s.ToString() << endl; 44``` 45 46## Closing A Database 47 48When you are done with a database, just delete the database object. Example: 49 50```c++ 51... open the db as described above ... 52... do something with db ... 53delete db; 54``` 55 56## Reads And Writes 57 58The database provides Put, Delete, and Get methods to modify/query the database. 59For example, the following code moves the value stored under key1 to key2. 60 61```c++ 62std::string value; 63leveldb::Status s = db->Get(leveldb::ReadOptions(), key1, &value); 64if (s.ok()) s = db->Put(leveldb::WriteOptions(), key2, value); 65if (s.ok()) s = db->Delete(leveldb::WriteOptions(), key1); 66``` 67 68## Atomic Updates 69 70Note that if the process dies after the Put of key2 but before the delete of 71key1, the same value may be left stored under multiple keys. Such problems can 72be avoided by using the `WriteBatch` class to atomically apply a set of updates: 73 74```c++ 75#include "leveldb/write_batch.h" 76... 77std::string value; 78leveldb::Status s = db->Get(leveldb::ReadOptions(), key1, &value); 79if (s.ok()) { 80 leveldb::WriteBatch batch; 81 batch.Delete(key1); 82 batch.Put(key2, value); 83 s = db->Write(leveldb::WriteOptions(), &batch); 84} 85``` 86 87The `WriteBatch` holds a sequence of edits to be made to the database, and these 88edits within the batch are applied in order. Note that we called Delete before 89Put so that if key1 is identical to key2, we do not end up erroneously dropping 90the value entirely. 91 92Apart from its atomicity benefits, `WriteBatch` may also be used to speed up 93bulk updates by placing lots of individual mutations into the same batch. 94 95## Synchronous Writes 96 97By default, each write to leveldb is asynchronous: it returns after pushing the 98write from the process into the operating system. The transfer from operating 99system memory to the underlying persistent storage happens asynchronously. The 100sync flag can be turned on for a particular write to make the write operation 101not return until the data being written has been pushed all the way to 102persistent storage. (On Posix systems, this is implemented by calling either 103`fsync(...)` or `fdatasync(...)` or `msync(..., MS_SYNC)` before the write 104operation returns.) 105 106```c++ 107leveldb::WriteOptions write_options; 108write_options.sync = true; 109db->Put(write_options, ...); 110``` 111 112Asynchronous writes are often more than a thousand times as fast as synchronous 113writes. The downside of asynchronous writes is that a crash of the machine may 114cause the last few updates to be lost. Note that a crash of just the writing 115process (i.e., not a reboot) will not cause any loss since even when sync is 116false, an update is pushed from the process memory into the operating system 117before it is considered done. 118 119Asynchronous writes can often be used safely. For example, when loading a large 120amount of data into the database you can handle lost updates by restarting the 121bulk load after a crash. A hybrid scheme is also possible where every Nth write 122is synchronous, and in the event of a crash, the bulk load is restarted just 123after the last synchronous write finished by the previous run. (The synchronous 124write can update a marker that describes where to restart on a crash.) 125 126`WriteBatch` provides an alternative to asynchronous writes. Multiple updates 127may be placed in the same WriteBatch and applied together using a synchronous 128write (i.e., `write_options.sync` is set to true). The extra cost of the 129synchronous write will be amortized across all of the writes in the batch. 130 131## Concurrency 132 133A database may only be opened by one process at a time. The leveldb 134implementation acquires a lock from the operating system to prevent misuse. 135Within a single process, the same `leveldb::DB` object may be safely shared by 136multiple concurrent threads. I.e., different threads may write into or fetch 137iterators or call Get on the same database without any external synchronization 138(the leveldb implementation will automatically do the required synchronization). 139However other objects (like Iterator and `WriteBatch`) may require external 140synchronization. If two threads share such an object, they must protect access 141to it using their own locking protocol. More details are available in the public 142header files. 143 144## Iteration 145 146The following example demonstrates how to print all key,value pairs in a 147database. 148 149```c++ 150leveldb::Iterator* it = db->NewIterator(leveldb::ReadOptions()); 151for (it->SeekToFirst(); it->Valid(); it->Next()) { 152 cout << it->key().ToString() << ": " << it->value().ToString() << endl; 153} 154assert(it->status().ok()); // Check for any errors found during the scan 155delete it; 156``` 157 158The following variation shows how to process just the keys in the range 159[start,limit): 160 161```c++ 162for (it->Seek(start); 163 it->Valid() && it->key().ToString() < limit; 164 it->Next()) { 165 ... 166} 167``` 168 169You can also process entries in reverse order. (Caveat: reverse iteration may be 170somewhat slower than forward iteration.) 171 172```c++ 173for (it->SeekToLast(); it->Valid(); it->Prev()) { 174 ... 175} 176``` 177 178## Snapshots 179 180Snapshots provide consistent read-only views over the entire state of the 181key-value store. `ReadOptions::snapshot` may be non-NULL to indicate that a 182read should operate on a particular version of the DB state. If 183`ReadOptions::snapshot` is NULL, the read will operate on an implicit snapshot 184of the current state. 185 186Snapshots are created by the `DB::GetSnapshot()` method: 187 188```c++ 189leveldb::ReadOptions options; 190options.snapshot = db->GetSnapshot(); 191... apply some updates to db ... 192leveldb::Iterator* iter = db->NewIterator(options); 193... read using iter to view the state when the snapshot was created ... 194delete iter; 195db->ReleaseSnapshot(options.snapshot); 196``` 197 198Note that when a snapshot is no longer needed, it should be released using the 199`DB::ReleaseSnapshot` interface. This allows the implementation to get rid of 200state that was being maintained just to support reading as of that snapshot. 201 202## Slice 203 204The return value of the `it->key()` and `it->value()` calls above are instances 205of the `leveldb::Slice` type. Slice is a simple structure that contains a length 206and a pointer to an external byte array. Returning a Slice is a cheaper 207alternative to returning a `std::string` since we do not need to copy 208potentially large keys and values. In addition, leveldb methods do not return 209null-terminated C-style strings since leveldb keys and values are allowed to 210contain `'\0'` bytes. 211 212C++ strings and null-terminated C-style strings can be easily converted to a 213Slice: 214 215```c++ 216leveldb::Slice s1 = "hello"; 217 218std::string str("world"); 219leveldb::Slice s2 = str; 220``` 221 222A Slice can be easily converted back to a C++ string: 223 224```c++ 225std::string str = s1.ToString(); 226assert(str == std::string("hello")); 227``` 228 229Be careful when using Slices since it is up to the caller to ensure that the 230external byte array into which the Slice points remains live while the Slice is 231in use. For example, the following is buggy: 232 233```c++ 234leveldb::Slice slice; 235if (...) { 236 std::string str = ...; 237 slice = str; 238} 239Use(slice); 240``` 241 242When the if statement goes out of scope, str will be destroyed and the backing 243storage for slice will disappear. 244 245## Comparators 246 247The preceding examples used the default ordering function for key, which orders 248bytes lexicographically. You can however supply a custom comparator when opening 249a database. For example, suppose each database key consists of two numbers and 250we should sort by the first number, breaking ties by the second number. First, 251define a proper subclass of `leveldb::Comparator` that expresses these rules: 252 253```c++ 254class TwoPartComparator : public leveldb::Comparator { 255 public: 256 // Three-way comparison function: 257 // if a < b: negative result 258 // if a > b: positive result 259 // else: zero result 260 int Compare(const leveldb::Slice& a, const leveldb::Slice& b) const { 261 int a1, a2, b1, b2; 262 ParseKey(a, &a1, &a2); 263 ParseKey(b, &b1, &b2); 264 if (a1 < b1) return -1; 265 if (a1 > b1) return +1; 266 if (a2 < b2) return -1; 267 if (a2 > b2) return +1; 268 return 0; 269 } 270 271 // Ignore the following methods for now: 272 const char* Name() const { return "TwoPartComparator"; } 273 void FindShortestSeparator(std::string*, const leveldb::Slice&) const {} 274 void FindShortSuccessor(std::string*) const {} 275}; 276``` 277 278Now create a database using this custom comparator: 279 280```c++ 281TwoPartComparator cmp; 282leveldb::DB* db; 283leveldb::Options options; 284options.create_if_missing = true; 285options.comparator = &cmp; 286leveldb::Status status = leveldb::DB::Open(options, "/tmp/testdb", &db); 287... 288``` 289 290### Backwards compatibility 291 292The result of the comparator's Name method is attached to the database when it 293is created, and is checked on every subsequent database open. If the name 294changes, the `leveldb::DB::Open` call will fail. Therefore, change the name if 295and only if the new key format and comparison function are incompatible with 296existing databases, and it is ok to discard the contents of all existing 297databases. 298 299You can however still gradually evolve your key format over time with a little 300bit of pre-planning. For example, you could store a version number at the end of 301each key (one byte should suffice for most uses). When you wish to switch to a 302new key format (e.g., adding an optional third part to the keys processed by 303`TwoPartComparator`), (a) keep the same comparator name (b) increment the 304version number for new keys (c) change the comparator function so it uses the 305version numbers found in the keys to decide how to interpret them. 306 307## Performance 308 309Performance can be tuned by changing the default values of the types defined in 310`include/options.h`. 311 312### Block size 313 314leveldb groups adjacent keys together into the same block and such a block is 315the unit of transfer to and from persistent storage. The default block size is 316approximately 4096 uncompressed bytes. Applications that mostly do bulk scans 317over the contents of the database may wish to increase this size. Applications 318that do a lot of point reads of small values may wish to switch to a smaller 319block size if performance measurements indicate an improvement. There isn't much 320benefit in using blocks smaller than one kilobyte, or larger than a few 321megabytes. Also note that compression will be more effective with larger block 322sizes. 323 324### Compression 325 326Each block is individually compressed before being written to persistent 327storage. Compression is on by default since the default compression method is 328very fast, and is automatically disabled for uncompressible data. In rare cases, 329applications may want to disable compression entirely, but should only do so if 330benchmarks show a performance improvement: 331 332```c++ 333leveldb::Options options; 334options.compression = leveldb::kNoCompression; 335... leveldb::DB::Open(options, name, ...) .... 336``` 337 338### Cache 339 340The contents of the database are stored in a set of files in the filesystem and 341each file stores a sequence of compressed blocks. If options.block_cache is 342non-NULL, it is used to cache frequently used uncompressed block contents. 343 344```c++ 345#include "leveldb/cache.h" 346 347leveldb::Options options; 348options.block_cache = leveldb::NewLRUCache(100 * 1048576); // 100MB cache 349leveldb::DB* db; 350leveldb::DB::Open(options, name, &db); 351... use the db ... 352delete db 353delete options.block_cache; 354``` 355 356Note that the cache holds uncompressed data, and therefore it should be sized 357according to application level data sizes, without any reduction from 358compression. (Caching of compressed blocks is left to the operating system 359buffer cache, or any custom Env implementation provided by the client.) 360 361When performing a bulk read, the application may wish to disable caching so that 362the data processed by the bulk read does not end up displacing most of the 363cached contents. A per-iterator option can be used to achieve this: 364 365```c++ 366leveldb::ReadOptions options; 367options.fill_cache = false; 368leveldb::Iterator* it = db->NewIterator(options); 369for (it->SeekToFirst(); it->Valid(); it->Next()) { 370 ... 371} 372``` 373 374### Key Layout 375 376Note that the unit of disk transfer and caching is a block. Adjacent keys 377(according to the database sort order) will usually be placed in the same block. 378Therefore the application can improve its performance by placing keys that are 379accessed together near each other and placing infrequently used keys in a 380separate region of the key space. 381 382For example, suppose we are implementing a simple file system on top of leveldb. 383The types of entries we might wish to store are: 384 385 filename -> permission-bits, length, list of file_block_ids 386 file_block_id -> data 387 388We might want to prefix filename keys with one letter (say '/') and the 389`file_block_id` keys with a different letter (say '0') so that scans over just 390the metadata do not force us to fetch and cache bulky file contents. 391 392### Filters 393 394Because of the way leveldb data is organized on disk, a single `Get()` call may 395involve multiple reads from disk. The optional FilterPolicy mechanism can be 396used to reduce the number of disk reads substantially. 397 398```c++ 399leveldb::Options options; 400options.filter_policy = NewBloomFilterPolicy(10); 401leveldb::DB* db; 402leveldb::DB::Open(options, "/tmp/testdb", &db); 403... use the database ... 404delete db; 405delete options.filter_policy; 406``` 407 408The preceding code associates a Bloom filter based filtering policy with the 409database. Bloom filter based filtering relies on keeping some number of bits of 410data in memory per key (in this case 10 bits per key since that is the argument 411we passed to `NewBloomFilterPolicy`). This filter will reduce the number of 412unnecessary disk reads needed for Get() calls by a factor of approximately 413a 100. Increasing the bits per key will lead to a larger reduction at the cost 414of more memory usage. We recommend that applications whose working set does not 415fit in memory and that do a lot of random reads set a filter policy. 416 417If you are using a custom comparator, you should ensure that the filter policy 418you are using is compatible with your comparator. For example, consider a 419comparator that ignores trailing spaces when comparing keys. 420`NewBloomFilterPolicy` must not be used with such a comparator. Instead, the 421application should provide a custom filter policy that also ignores trailing 422spaces. For example: 423 424```c++ 425class CustomFilterPolicy : public leveldb::FilterPolicy { 426 private: 427 FilterPolicy* builtin_policy_; 428 429 public: 430 CustomFilterPolicy() : builtin_policy_(NewBloomFilterPolicy(10)) {} 431 ~CustomFilterPolicy() { delete builtin_policy_; } 432 433 const char* Name() const { return "IgnoreTrailingSpacesFilter"; } 434 435 void CreateFilter(const Slice* keys, int n, std::string* dst) const { 436 // Use builtin bloom filter code after removing trailing spaces 437 std::vector<Slice> trimmed(n); 438 for (int i = 0; i < n; i++) { 439 trimmed[i] = RemoveTrailingSpaces(keys[i]); 440 } 441 return builtin_policy_->CreateFilter(trimmed.data(), n, dst); 442 } 443}; 444``` 445 446Advanced applications may provide a filter policy that does not use a bloom 447filter but uses some other mechanism for summarizing a set of keys. See 448`leveldb/filter_policy.h` for detail. 449 450## Checksums 451 452leveldb associates checksums with all data it stores in the file system. There 453are two separate controls provided over how aggressively these checksums are 454verified: 455 456`ReadOptions::verify_checksums` may be set to true to force checksum 457verification of all data that is read from the file system on behalf of a 458particular read. By default, no such verification is done. 459 460`Options::paranoid_checks` may be set to true before opening a database to make 461the database implementation raise an error as soon as it detects an internal 462corruption. Depending on which portion of the database has been corrupted, the 463error may be raised when the database is opened, or later by another database 464operation. By default, paranoid checking is off so that the database can be used 465even if parts of its persistent storage have been corrupted. 466 467If a database is corrupted (perhaps it cannot be opened when paranoid checking 468is turned on), the `leveldb::RepairDB` function may be used to recover as much 469of the data as possible 470 471## Approximate Sizes 472 473The `GetApproximateSizes` method can used to get the approximate number of bytes 474of file system space used by one or more key ranges. 475 476```c++ 477leveldb::Range ranges[2]; 478ranges[0] = leveldb::Range("a", "c"); 479ranges[1] = leveldb::Range("x", "z"); 480uint64_t sizes[2]; 481db->GetApproximateSizes(ranges, 2, sizes); 482``` 483 484The preceding call will set `sizes[0]` to the approximate number of bytes of 485file system space used by the key range `[a..c)` and `sizes[1]` to the 486approximate number of bytes used by the key range `[x..z)`. 487 488## Environment 489 490All file operations (and other operating system calls) issued by the leveldb 491implementation are routed through a `leveldb::Env` object. Sophisticated clients 492may wish to provide their own Env implementation to get better control. 493For example, an application may introduce artificial delays in the file IO 494paths to limit the impact of leveldb on other activities in the system. 495 496```c++ 497class SlowEnv : public leveldb::Env { 498 ... implementation of the Env interface ... 499}; 500 501SlowEnv env; 502leveldb::Options options; 503options.env = &env; 504Status s = leveldb::DB::Open(options, ...); 505``` 506 507## Porting 508 509leveldb may be ported to a new platform by providing platform specific 510implementations of the types/methods/functions exported by 511`leveldb/port/port.h`. See `leveldb/port/port_example.h` for more details. 512 513In addition, the new platform may need a new default `leveldb::Env` 514implementation. See `leveldb/util/env_posix.h` for an example. 515 516## Other Information 517 518Details about the leveldb implementation may be found in the following 519documents: 520 5211. [Implementation notes](impl.md) 5222. [Format of an immutable Table file](table_format.md) 5233. [Format of a log file](log_format.md) 524