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> 12 The <code>leveldb</code> library provides a persistent key value store. Keys and 13 values are arbitrary byte arrays. The keys are ordered within the key 14 value store according to a user-specified comparator function. 15 16 <p> 17 <h1>Opening A Database</h1> 18 <p> 19 A <code>leveldb</code> database has a name which corresponds to a file system 20 directory. All of the contents of database are stored in this 21 directory. The following example shows how to open a database, 22 creating 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> 35 If you want to raise an error if the database already exists, add 36 the 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> 42 You may have noticed the <code>leveldb::Status</code> type above. Values of this 43 type are returned by most functions in <code>leveldb</code> that may encounter an 44 error. You can check if such a result is ok, and also print an 45 associated 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> 53 When you are done with a database, just delete the database object. 54 Example: 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> 63 The database provides <code>Put</code>, <code>Delete</code>, and <code>Get</code> methods to 64 modify/query the database. For example, the following code 65 moves 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> 75 Note that if the process dies after the Put of key2 but before the 76 delete of key1, the same value may be left stored under multiple keys. 77 Such problems can be avoided by using the <code>WriteBatch</code> class to 78 atomically 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> 92 The <code>WriteBatch</code> holds a sequence of edits to be made to the database, 93 and these edits within the batch are applied in order. Note that we 94 called <code>Delete</code> before <code>Put</code> so that if <code>key1</code> is identical to <code>key2</code>, 95 we do not end up erroneously dropping the value entirely. 96 <p> 97 Apart from its atomicity benefits, <code>WriteBatch</code> may also be used to 98 speed up bulk updates by placing lots of individual mutations into the 99 same batch. 100 101 <h1>Synchronous Writes</h1> 102 By default, each write to <code>leveldb</code> is asynchronous: it 103 returns after pushing the write from the process into the operating 104 system. The transfer from operating system memory to the underlying 105 persistent storage happens asynchronously. The <code>sync</code> flag 106 can be turned on for a particular write to make the write operation 107 not return until the data being written has been pushed all the way to 108 persistent storage. (On Posix systems, this is implemented by calling 109 either <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> 116 Asynchronous writes are often more than a thousand times as fast as 117 synchronous writes. The downside of asynchronous writes is that a 118 crash of the machine may cause the last few updates to be lost. Note 119 that a crash of just the writing process (i.e., not a reboot) will not 120 cause any loss since even when <code>sync</code> is false, an update 121 is pushed from the process memory into the operating system before it 122 is considered done. 123 124 <p> 125 Asynchronous writes can often be used safely. For example, when 126 loading a large amount of data into the database you can handle lost 127 updates by restarting the bulk load after a crash. A hybrid scheme is 128 also possible where every Nth write is synchronous, and in the event 129 of a crash, the bulk load is restarted just after the last synchronous 130 write finished by the previous run. (The synchronous write can update 131 a marker that describes where to restart on a crash.) 132 133 <p> 134 <code>WriteBatch</code> provides an alternative to asynchronous writes. 135 Multiple updates may be placed in the same <code>WriteBatch</code> and 136 applied together using a synchronous write (i.e., 137 <code>write_options.sync</code> is set to true). The extra cost of 138 the synchronous write will be amortized across all of the writes in 139 the batch. 140 141 <p> 142 <h1>Concurrency</h1> 143 <p> 144 A database may only be opened by one process at a time. 145 The <code>leveldb</code> implementation acquires a lock from the 146 operating system to prevent misuse. Within a single process, the 147 same <code>leveldb::DB</code> object may be safely shared by multiple 148 concurrent threads. I.e., different threads may write into or fetch 149 iterators or call <code>Get</code> on the same database without any 150 external synchronization (the leveldb implementation will 151 automatically do the required synchronization). However other objects 152 (like Iterator and WriteBatch) may require external synchronization. 153 If two threads share such an object, they must protect access to it 154 using their own locking protocol. More details are available in 155 the public header files. 156 <p> 157 <h1>Iteration</h1> 158 <p> 159 The following example demonstrates how to print all key,value pairs 160 in 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> 170 The following variation shows how to process just the keys in the 171 range <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> 180 You can also process entries in reverse order. (Caveat: reverse 181 iteration 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> 190 Snapshots provide consistent read-only views over the entire state of 191 the key-value store. <code>ReadOptions::snapshot</code> may be non-NULL to indicate 192 that a read should operate on a particular version of the DB state. 193 If <code>ReadOptions::snapshot</code> is NULL, the read will operate on an 194 implicit snapshot of the current state. 195 <p> 196 Snapshots 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> 207 Note that when a snapshot is no longer needed, it should be released 208 using the DB::ReleaseSnapshot interface. This allows the 209 implementation to get rid of state that was being maintained just to 210 support reading as of that snapshot. 211 <h1>Slice</h1> 212 <p> 213 The return value of the <code>it->key()</code> and <code>it->value()</code> calls above 214 are instances of the <code>leveldb::Slice</code> type. <code>Slice</code> is a simple 215 structure that contains a length and a pointer to an external byte 216 array. 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 218 values. In addition, <code>leveldb</code> methods do not return null-terminated 219 C-style strings since <code>leveldb</code> keys and values are allowed to 220 contain '\0' bytes. 221 <p> 222 C++ strings and null-terminated C-style strings can be easily converted 223 to a Slice: 224 <p> 225 <pre> 226 leveldb::Slice s1 = "hello"; 227 228 std::string str("world"); 229 leveldb::Slice s2 = str; 230 </pre> 231 A 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> 236 Be careful when using Slices since it is up to the caller to ensure that 237 the external byte array into which the Slice points remains live while 238 the 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> 248 When the <code>if</code> statement goes out of scope, <code>str</code> will be destroyed and the 249 backing storage for <code>slice</code> will disappear. 250 <p> 251 <h1>Comparators</h1> 252 <p> 253 The preceding examples used the default ordering function for key, 254 which orders bytes lexicographically. You can however supply a custom 255 comparator when opening a database. For example, suppose each 256 database key consists of two numbers and we should sort by the first 257 number, breaking ties by the second number. First, define a proper 258 subclass 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> 284 Now 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> 297 The result of the comparator's <code>Name</code> method is attached to the 298 database when it is created, and is checked on every subsequent 299 database open. If the name changes, the <code>leveldb::DB::Open</code> call will 300 fail. Therefore, change the name if and only if the new key format 301 and comparison function are incompatible with existing databases, and 302 it is ok to discard the contents of all existing databases. 303 <p> 304 You can however still gradually evolve your key format over time with 305 a little bit of pre-planning. For example, you could store a version 306 number at the end of each key (one byte should suffice for most uses). 307 When you wish to switch to a new key format (e.g., adding an optional 308 third part to the keys processed by <code>TwoPartComparator</code>), 309 (a) keep the same comparator name (b) increment the version number 310 for new keys (c) change the comparator function so it uses the 311 version numbers found in the keys to decide how to interpret them. 312 <p> 313 <h1>Performance</h1> 314 <p> 315 Performance can be tuned by changing the default values of the 316 types 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 322 block is the unit of transfer to and from persistent storage. The 323 default block size is approximately 4096 uncompressed bytes. 324 Applications that mostly do bulk scans over the contents of the 325 database may wish to increase this size. Applications that do a lot 326 of point reads of small values may wish to switch to a smaller block 327 size if performance measurements indicate an improvement. There isn't 328 much benefit in using blocks smaller than one kilobyte, or larger than 329 a few megabytes. Also note that compression will be more effective 330 with larger block sizes. 331 <p> 332 <h2>Compression</h2> 333 <p> 334 Each block is individually compressed before being written to 335 persistent storage. Compression is on by default since the default 336 compression method is very fast, and is automatically disabled for 337 uncompressible data. In rare cases, applications may want to disable 338 compression entirely, but should only do so if benchmarks show a 339 performance 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> 348 The contents of the database are stored in a set of files in the 349 filesystem 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 351 uncompressed 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> 364 Note that the cache holds uncompressed data, and therefore it should 365 be sized according to application level data sizes, without any 366 reduction from compression. (Caching of compressed blocks is left to 367 the operating system buffer cache, or any custom <code>Env</code> 368 implementation provided by the client.) 369 <p> 370 When performing a bulk read, the application may wish to disable 371 caching so that the data processed by the bulk read does not end up 372 displacing most of the cached contents. A per-iterator option can be 373 used 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> 385 Note that the unit of disk transfer and caching is a block. Adjacent 386 keys (according to the database sort order) will usually be placed in 387 the same block. Therefore the application can improve its performance 388 by placing keys that are accessed together near each other and placing 389 infrequently used keys in a separate region of the key space. 390 <p> 391 For example, suppose we are implementing a simple file system on top 392 of <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> 398 We 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 400 over just the metadata do not force us to fetch and cache bulky file 401 contents. 402 <p> 403 <h2>Filters</h2> 404 <p> 405 Because of the way <code>leveldb</code> data is organized on disk, 406 a single <code>Get()</code> call may involve multiple reads from disk. 407 The optional <code>FilterPolicy</code> mechanism can be used to reduce 408 the 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> 418 The preceding code associates a 419 <a href="http://en.wikipedia.org/wiki/Bloom_filter">Bloom filter</a> 420 based filtering policy with the database. Bloom filter based 421 filtering relies on keeping some number of bits of data in memory per 422 key (in this case 10 bits per key since that is the argument we passed 423 to NewBloomFilterPolicy). This filter will reduce the number of unnecessary 424 disk reads needed for <code>Get()</code> calls by a factor of 425 approximately a 100. Increasing the bits per key will lead to a 426 larger reduction at the cost of more memory usage. We recommend that 427 applications whose working set does not fit in memory and that do a 428 lot of random reads set a filter policy. 429 <p> 430 If you are using a custom comparator, you should ensure that the filter 431 policy you are using is compatible with your comparator. For example, 432 consider a comparator that ignores trailing spaces when comparing keys. 433 <code>NewBloomFilterPolicy</code> must not be used with such a comparator. 434 Instead, the application should provide a custom filter policy that 435 also 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> 462 Advanced applications may provide a filter policy that does not use 463 a bloom filter but uses some other mechanism for summarizing a set 464 of 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. 469 There are two separate controls provided over how aggressively these 470 checksums 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> 493 The <code>GetApproximateSizes</code> method can used to get the approximate 494 number 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> 503 The preceding call will set <code>sizes[0]</code> to the approximate number of 504 bytes 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> 510 All file operations (and other operating system calls) issued by the 511 <code>leveldb</code> implementation are routed through a <code>leveldb::Env</code> object. 512 Sophisticated clients may wish to provide their own <code>Env</code> 513 implementation to get better control. For example, an application may 514 introduce artificial delays in the file IO paths to limit the impact 515 of <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 530 specific 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 532 details. 533 <p> 534 In addition, the new platform may need a new default <code>leveldb::Env</code> 535 implementation. See <code>leveldb/util/env_posix.h</code> for an example. 536 537 <h1>Other Information</h1> 538 539 <p> 540 Details about the <code>leveldb</code> implementation may be found in 541 the 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