大家好,又见面了,我是你们的朋友全栈君。
网上有很多关于leveldb的介绍文章,还不如直接看官方文档,直接上文档,希望自己以后有空翻译成中文版本。
leveldb
Jeff Dean, Sanjay Ghemawat
The leveldb library provides a persistent key value store. Keys and values are arbitrary byte arrays. The keys are ordered within the key value store according to a user-specified comparator function.
Opening A Database
A leveldb database has a name which corresponds to a file system directory. All of the contents of database are stored in this directory. The following example shows how to open a database, creating it if necessary:
代码语言:javascript复制#include <cassert>
#include "leveldb/db.h"
leveldb::DB* db;
leveldb::Options options;
options.create_if_missing = true;
leveldb::Status status = leveldb::DB::Open(options, "/tmp/testdb", &db);
assert(status.ok());
...
If you want to raise an error if the database already exists, add the following
line before the leveldb::DB::Open
call:
options.error_if_exists = true;
Status
You may have noticed the leveldb::Status
type above. Values of this type are
returned by most functions in leveldb that may encounter an error. You can check
if such a result is ok, and also print an associated error message:
leveldb::Status s = ...;
if (!s.ok()) cerr << s.ToString() << endl;
Closing A Database
When you are done with a database, just delete the database object. Example:
代码语言:javascript复制... open the db as described above ...
... do something with db ...
delete db;
Reads And Writes
The database provides Put, Delete, and Get methods to modify/query the database. For example, the following code moves the value stored under key1 to key2.
代码语言:javascript复制std::string value;
leveldb::Status s = db->Get(leveldb::ReadOptions(), key1, &value);
if (s.ok()) s = db->Put(leveldb::WriteOptions(), key2, value);
if (s.ok()) s = db->Delete(leveldb::WriteOptions(), key1);
Atomic Updates
Note that if the process dies after the Put of key2 but before the delete of
key1, the same value may be left stored under multiple keys. Such problems can
be avoided by using the WriteBatch
class to atomically apply a set of updates:
#include "leveldb/write_batch.h"
...
std::string value;
leveldb::Status s = db->Get(leveldb::ReadOptions(), key1, &value);
if (s.ok()) {
leveldb::WriteBatch batch;
batch.Delete(key1);
batch.Put(key2, value);
s = db->Write(leveldb::WriteOptions(), &batch);
}
The WriteBatch
holds a sequence of edits to be made to the database, and these
edits within the batch are applied in order. Note that we called Delete before
Put so that if key1 is identical to key2, we do not end up erroneously dropping
the value entirely.
Apart from its atomicity benefits, WriteBatch
may also be used to speed up
bulk updates by placing lots of individual mutations into the same batch.
Synchronous Writes
By default, each write to leveldb is asynchronous: it returns after pushing the
write from the process into the operating system. The transfer from operating
system memory to the underlying persistent storage happens asynchronously. The
sync flag can be turned on for a particular write to make the write operation
not return until the data being written has been pushed all the way to
persistent storage. (On Posix systems, this is implemented by calling either
fsync(...)
or fdatasync(...)
or msync(..., MS_SYNC)
before the write
operation returns.)
leveldb::WriteOptions write_options;
write_options.sync = true;
db->Put(write_options, ...);
Asynchronous writes are often more than a thousand times as fast as synchronous writes. The downside of asynchronous writes is that a crash of the machine may cause the last few updates to be lost. Note that a crash of just the writing process (i.e., not a reboot) will not cause any loss since even when sync is false, an update is pushed from the process memory into the operating system before it is considered done.
Asynchronous writes can often be used safely. For example, when loading a large amount of data into the database you can handle lost updates by restarting the bulk load after a crash. A hybrid scheme is also possible where every Nth write is synchronous, and in the event of a crash, the bulk load is restarted just after the last synchronous write finished by the previous run. (The synchronous write can update a marker that describes where to restart on a crash.)
WriteBatch
provides an alternative to asynchronous writes. Multiple updates
may be placed in the same WriteBatch and applied together using a synchronous
write (i.e., write_options.sync
is set to true). The extra cost of the
synchronous write will be amortized across all of the writes in the batch.
Concurrency
A database may only be opened by one process at a time. The leveldb
implementation acquires a lock from the operating system to prevent misuse.
Within a single process, the same leveldb::DB
object may be safely shared by
multiple concurrent threads. I.e., different threads may write into or fetch
iterators or call Get on the same database without any external synchronization
(the leveldb implementation will automatically do the required synchronization).
However other objects (like Iterator and WriteBatch
) may require external
synchronization. If two threads share such an object, they must protect access
to it using their own locking protocol. More details are available in the public
header files.
Iteration
The following example demonstrates how to print all key,value pairs in a database.
代码语言:javascript复制leveldb::Iterator* it = db->NewIterator(leveldb::ReadOptions());
for (it->SeekToFirst(); it->Valid(); it->Next()) {
cout << it->key().ToString() << ": " << it->value().ToString() << endl;
}
assert(it->status().ok()); // Check for any errors found during the scan
delete it;
The following variation shows how to process just the keys in the range [start,limit):
代码语言:javascript复制for (it->Seek(start);
it->Valid() && it->key().ToString() < limit;
it->Next()) {
...
}
You can also process entries in reverse order. (Caveat: reverse iteration may be somewhat slower than forward iteration.)
代码语言:javascript复制for (it->SeekToLast(); it->Valid(); it->Prev()) {
...
}
Snapshots
Snapshots provide consistent read-only views over the entire state of the
key-value store. ReadOptions::snapshot
may be non-NULL to indicate that a
read should operate on a particular version of the DB state. If
ReadOptions::snapshot
is NULL, the read will operate on an implicit snapshot
of the current state.
Snapshots are created by the DB::GetSnapshot()
method:
leveldb::ReadOptions options;
options.snapshot = db->GetSnapshot();
... apply some updates to db ...
leveldb::Iterator* iter = db->NewIterator(options);
... read using iter to view the state when the snapshot was created ...
delete iter;
db->ReleaseSnapshot(options.snapshot);
Note that when a snapshot is no longer needed, it should be released using the
DB::ReleaseSnapshot
interface. This allows the implementation to get rid of
state that was being maintained just to support reading as of that snapshot.
Slice
The return value of the it->key()
and it->value()
calls above are instances
of the leveldb::Slice
type. Slice is a simple structure that contains a length
and a pointer to an external byte array. Returning a Slice is a cheaper
alternative to returning a std::string
since we do not need to copy
potentially large keys and values. In addition, leveldb methods do not return
null-terminated C-style strings since leveldb keys and values are allowed to
contain '