作者: 韩晨旭 10225101440 李畅 10225102463
Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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