作者: 谢瑞阳 10225101483 徐翔宇 10225101535
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.

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