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