levelDB是google开源的一个key-value存储引擎库,类似于开源的Lucene索引库一样。其他的软件开发者可以利用该库做二次开发,来满足定制需求。LevelDB采用日志式的写方式来提高写性能,但是牺牲了部分读性能。为了弥补牺牲了的读性能,一些人提议使用SSD作为存储介质。
对于本地化的Key-value存储引擎来说,简单的使用一般都分成三个基本的步骤:(1)打开一个数据库实例;(2)对这个数据库实例进行插入,修改和查询操作;(3)最后在使用完成之后,关闭该数据库。
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:#include <assert>
#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:... 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.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);
测试程序示例
#include <assert.h>
#include <iostream>
#include "leveldb/db.h"
using namespace std;
using namespace leveldb;
int main()
{
DB* db;
Options options;
options.create_if_missing = true;
//options.error_if_exists = true;
Status status = DB::Open(options, "/tmp/testdb", &db);
assert(status.ok());
cout << status.ToString() << endl;
string key1 = "hdu1", value1 = "123";
string key2 = "hdu2", value2 = "456";
string value;
db->Put(WriteOptions(), key1, value1);
db->Put(WriteOptions(), key2, value2);
status = db->Get(ReadOptions(), key1, &value);
if (status.ok())
status = db->Put(WriteOptions(), key2, value);
//if (status.ok())
// status = db->Delete(WriteOptions(), key1);
status = db->Get(ReadOptions(), key1, &value);
if (status.ok())
cout << key1 << ": " << value << endl;
status = db->Get(ReadOptions(), key2, &value);
if (status.ok())
cout << key2 << ": " << value << endl;
delete db;
return 0;
}
编译程序
命令:g++ -o test test.cpp /home/luox28/leveldb/libleveldb.a -I/home/luox28/leveldb/include -lpthread
当然,在下载好了leveldb源码后,进入到leveldb主目录,编译源码。 cd leveldb && make all
参考资料
1、leveldb自带doc文档