10225501448 李度 10225101546 陈胤遒 10215501422 高宇菲
25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

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