小组成员:谢瑞阳、徐翔宇
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

508 lines
19 KiB

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