levelDB 使用笔记
2022-02-26 update:
说学习笔记听起来像在分析代码。。。但是实际上什么都没干,还是写"使用笔记"好了
大三的时候看过一点levelDB的源码,不过没有怎么用过。
最近有个需求是存人脸的feature到硬盘,似乎使用levelDB比较合适,因此来学习一下使用。
先放参考资料。
关于levelDB的语法,看这里就好了。
以及由于caffe中使用了levelDB,因此也可以参考下caffe源码。不过caffe中对levelDB的使用是又封装了一层。
具体可以参考:
#ifdef USE_LEVELDB
#ifndef CAFFE_UTIL_DB_LEVELDB_HPP
#define CAFFE_UTIL_DB_LEVELDB_HPP
#include <string>
#include "leveldb/db.h"
#include "leveldb/write_batch.h"
#include "caffe/util/db.hpp"
namespace caffe { namespace db {
1class LevelDBCursor : public Cursor {
2 public:
3 explicit LevelDBCursor(leveldb::Iterator* iter)
4 : iter_(iter) {
5 SeekToFirst();
6 CHECK(iter_->status().ok()) << iter_->status().ToString();
7 }
8 ~LevelDBCursor() { delete iter_; }
9 virtual void SeekToFirst() { iter_->SeekToFirst(); }
10 virtual void Next() { iter_->Next(); }
11 virtual string key() { return iter_->key().ToString(); }
12 virtual string value() { return iter_->value().ToString(); }
13 virtual bool valid() { return iter_->Valid(); }
1 private:
2 leveldb::Iterator* iter_;
3};
1class LevelDBTransaction : public Transaction {
2 public:
3 explicit LevelDBTransaction(leveldb::DB* db) : db_(db) { CHECK_NOTNULL(db_); }
4 virtual void Put(const string& key, const string& value) {
5 batch_.Put(key, value);
6 }
7 virtual void Commit() {
8 leveldb::Status status = db_->Write(leveldb::WriteOptions(), &batch_);
9 CHECK(status.ok()) << "Failed to write batch to leveldb "
10 << std::endl << status.ToString();
11 }
1 private:
2 leveldb::DB* db_;
3 leveldb::WriteBatch batch_;
DISABLE_COPY_AND_ASSIGN(LevelDBTransaction);
};
1class LevelDB : public DB {
2 public:
3 LevelDB() : db_(NULL) { }
4 virtual ~LevelDB() { Close(); }
5 virtual void Open(const string& source, Mode mode);
6 virtual void Close() {
7 if (db_ != NULL) {
8 delete db_;
9 db_ = NULL;
10 }
11 }
12 virtual LevelDBCursor* NewCursor() {
13 return new LevelDBCursor(db_->NewIterator(leveldb::ReadOptions()));
14 }
15 virtual LevelDBTransaction* NewTransaction() {
16 return new LevelDBTransaction(db_);
17 }
1 private:
2 leveldb::DB* db_;
3};
} // namespace db
} // namespace caffe
#endif // CAFFE_UTIL_DB_LEVELDB_HPP
#endif // USE_LEVELDB
#ifndef CAFFE_UTIL_DB_HPP
#define CAFFE_UTIL_DB_HPP
#include <string>
#include "caffe/common.hpp"
#include "caffe/proto/caffe.pb.h"
namespace caffe { namespace db {
enum Mode { READ, WRITE, NEW };
1class Cursor {
2 public:
3 Cursor() { }
4 virtual ~Cursor() { }
5 virtual void SeekToFirst() = 0;
6 virtual void Next() = 0;
7 virtual string key() = 0;
8 virtual string value() = 0;
9 virtual bool valid() = 0;
DISABLE_COPY_AND_ASSIGN(Cursor);
};
1class Transaction {
2 public:
3 Transaction() { }
4 virtual ~Transaction() { }
5 virtual void Put(const string& key, const string& value) = 0;
6 virtual void Commit() = 0;
DISABLE_COPY_AND_ASSIGN(Transaction);
};
1class DB {
2 public:
3 DB() { }
4 virtual ~DB() { }
5 virtual void Open(const string& source, Mode mode) = 0;
6 virtual void Close() = 0;
7 virtual Cursor* NewCursor() = 0;
8 virtual Transaction* NewTransaction() = 0;
DISABLE_COPY_AND_ASSIGN(DB);
};
DB* GetDB(DataParameter::DB backend);
DB* GetDB(const string& backend);
} // namespace db
} // namespace caffe
#endif // CAFFE_UTIL_DB_HPP
#ifdef USE_LEVELDB
#include "caffe/util/db_leveldb.hpp"
#include <string>
namespace caffe { namespace db {
1void LevelDB::Open(const string& source, Mode mode) {
2 leveldb::Options options;
3 options.block_size = 65536;
4 options.write_buffer_size = 268435456;
5 options.max_open_files = 100;
6 options.error_if_exists = mode == NEW;
7 options.create_if_missing = mode != READ;
8 leveldb::Status status = leveldb::DB::Open(options, source, &db_);
9 CHECK(status.ok()) << "Failed to open leveldb " << source
10 << std::endl << status.ToString();
11 LOG(INFO) << "Opened leveldb " << source;
12}
1} // namespace db
2} // namespace caffe
3#endif // USE_LEVELDB
#include "caffe/util/db.hpp"
#include "caffe/util/db_leveldb.hpp"
#include "caffe/util/db_lmdb.hpp"
#include <string>
namespace caffe { namespace db {
1DB* GetDB(DataParameter::DB backend) {
2 switch (backend) {
3#ifdef USE_LEVELDB
4 case DataParameter_DB_LEVELDB:
5 return new LevelDB();
6#endif // USE_LEVELDB
7#ifdef USE_LMDB
8 case DataParameter_DB_LMDB:
9 return new LMDB();
10#endif // USE_LMDB
11 default:
12 LOG(FATAL) << "Unknown database backend";
13 return NULL;
14 }
15}
1DB* GetDB(const string& backend) {
2#ifdef USE_LEVELDB
3 if (backend == "leveldb") {
4 return new LevelDB();
5 }
6#endif // USE_LEVELDB
7#ifdef USE_LMDB
8 if (backend == "lmdb") {
9 return new LMDB();
10 }
11#endif // USE_LMDB
12 LOG(FATAL) << "Unknown database backend";
13 return NULL;
14}
} // namespace db
} // namespace caffe
1// This program converts a set of images to a lmdb/leveldb by storing them
2// as Datum proto buffers.
3// Usage:
4// convert_imageset [FLAGS] ROOTFOLDER/ LISTFILE DB_NAME
5//
6// where ROOTFOLDER is the root folder that holds all the images, and LISTFILE
7// should be a list of files as well as their labels, in the format as
8// subfolder1/file1.JPEG 7
9// ....
1#include <algorithm>
2#include <fstream> // NOLINT(readability/streams)
3#include <string>
4#include <utility>
5#include <vector>
#include "boost/scoped_ptr.hpp"
#include "gflags/gflags.h"
#include "glog/logging.h"
#include "caffe/proto/caffe.pb.h"
#include "caffe/util/db.hpp"
#include "caffe/util/format.hpp"
#include "caffe/util/io.hpp"
#include "caffe/util/rng.hpp"
1using namespace caffe; // NOLINT(build/namespaces)
2using std::pair;
3using boost::scoped_ptr;
1DEFINE_bool(gray, false,
2 "When this option is on, treat images as grayscale ones");
3DEFINE_bool(shuffle, false,
4 "Randomly shuffle the order of images and their labels");
5DEFINE_string(backend, "lmdb",
6 "The backend {lmdb, leveldb} for storing the result");
7DEFINE_int32(resize_width, 0, "Width images are resized to");
8DEFINE_int32(resize_height, 0, "Height images are resized to");
9DEFINE_bool(check_size, false,
10 "When this option is on, check that all the datum have the same size");
11DEFINE_bool(encoded, false,
12 "When this option is on, the encoded image will be save in datum");
13DEFINE_string(encode_type, "",
14 "Optional: What type should we encode the image as ('png','jpg',...).");
1int main(int argc, char** argv) {
2#ifdef USE_OPENCV
3 ::google::InitGoogleLogging(argv[0]);
4 // Print output to stderr (while still logging)
5 FLAGS_alsologtostderr = 1;
1#ifndef GFLAGS_GFLAGS_H_
2 namespace gflags = google;
3#endif
1 gflags::SetUsageMessage("Convert a set of images to the leveldb/lmdb\n"
2 "format used as input for Caffe.\n"
3 "Usage:\n"
4 " convert_imageset [FLAGS] ROOTFOLDER/ LISTFILE DB_NAME\n"
5 "The ImageNet dataset for the training demo is at\n"
6 " http://www.image-net.org/download-images\n");
7 gflags::ParseCommandLineFlags(&argc, &argv, true);
1 if (argc < 4) {
2 gflags::ShowUsageWithFlagsRestrict(argv[0], "tools/convert_imageset");
3 return 1;
4 }
1 const bool is_color = !FLAGS_gray;
2 const bool check_size = FLAGS_check_size;
3 const bool encoded = FLAGS_encoded;
4 const string encode_type = FLAGS_encode_type;
1 std::ifstream infile(argv[2]);
2 std::vector<std::pair<std::string, int> > lines;
3 std::string line;
4 size_t pos;
5 int label;
6 while (std::getline(infile, line)) {
7 pos = line.find_last_of(' ');
8 label = atoi(line.substr(pos + 1).c_str());
9 lines.push_back(std::make_pair(line.substr(0, pos), label));
10 }
11 if (FLAGS_shuffle) {
12 // randomly shuffle data
13 LOG(INFO) << "Shuffling data";
14 shuffle(lines.begin(), lines.end());
15 }
16 LOG(INFO) << "A total of " << lines.size() << " images.";
if (encode_type.size() && !encoded)
LOG(INFO) << "encode_type specified, assuming encoded=true.";
int resize_height = std::max<int>(0, FLAGS_resize_height);
int resize_width = std::max<int>(0, FLAGS_resize_width);
1 // Create new DB
2 scoped_ptr<db::DB> db(db::GetDB(FLAGS_backend));
3 db->Open(argv[3], db::NEW);
4 scoped_ptr<db::Transaction> txn(db->NewTransaction());
1 // Storing to db
2 std::string root_folder(argv[1]);
3 Datum datum;
4 int count = 0;
5 int data_size = 0;
6 bool data_size_initialized = false;
1 for (int line_id = 0; line_id < lines.size(); ++line_id) {
2 bool status;
3 std::string enc = encode_type;
4 if (encoded && !enc.size()) {
5 // Guess the encoding type from the file name
6 string fn = lines[line_id].first;
7 size_t p = fn.rfind('.');
8 if ( p == fn.npos )
9 LOG(WARNING) << "Failed to guess the encoding of '" << fn << "'";
10 enc = fn.substr(p+1);
11 std::transform(enc.begin(), enc.end(), enc.begin(), ::tolower);
12 }
13 status = ReadImageToDatum(root_folder + lines[line_id].first,
14 lines[line_id].second, resize_height, resize_width, is_color,
15 enc, &datum);
16 if (status == false) continue;
17 if (check_size) {
18 if (!data_size_initialized) {
19 data_size = datum.channels() * datum.height() * datum.width();
20 data_size_initialized = true;
21 } else {
22 const std::string& data = datum.data();
23 CHECK_EQ(data.size(), data_size) << "Incorrect data field size "
24 << data.size();
25 }
26 }
27 // sequential
28 string key_str = caffe::format_int(line_id, 8) + "_" + lines[line_id].first;
1 // Put in db
2 string out;
3 CHECK(datum.SerializeToString(&out));
4 txn->Put(key_str, out);
1 if (++count % 1000 == 0) {
2 // Commit db
3 txn->Commit();
4 txn.reset(db->NewTransaction());
5 LOG(INFO) << "Processed " << count << " files.";
6 }
7 }
8 // write the last batch
9 if (count % 1000 != 0) {
10 txn->Commit();
11 LOG(INFO) << "Processed " << count << " files.";
12 }
13#else
14 LOG(FATAL) << "This tool requires OpenCV; compile with USE_OPENCV.";
15#endif // USE_OPENCV
16 return 0;
17}
几个文件。。。感觉比看文档更有实际意义orz
levelDB简介
Leveldb是google开源的一个高效率的K/V数据库.有如下特点:
1. 首先,LevelDb是一个持久化存储的KV系统,和Redis这种内存型的KV系统不同,LevelDb不会像Redis一样狂吃内存,而是将大部分数据存储到磁盘上。
2. 其次,LevleDb在存储数据时,是根据记录的key值有序存储的,就是说相邻的key值在存储文件中是依次顺序存储的,而应用可以自定义key大小比较函数,LevleDb会按照用户定义的比较函数依序存储这些记录。
3. 再次,像大多数KV系统一样,LevelDb的操作接口很简单,基本操作包括写记录,读记录以及删除记录。也支持针对多条操作的原子批量操作。
4. 另外,LevelDb支持数据快照(snapshot)功能,使得读取操作不受写操作影响,可以在读操作过程中始终看到一致的数据。
5. 除此外,LevelDb还支持数据压缩等操作,这对于减小存储空间以及增快IO效率都有直接的帮助。
6. LevelDb性能非常突出,官方网站报道其随机写性能达到40万条记录每秒,而随机读性能达到6万条记录每秒。总体来说,LevelDb的写操作要大大快于读操作,而顺序读写操作则大大快于随机读写操作。
LevelDB的安装
以ubuntu14.04为例,但实际上除了路径可能不同,其他部分是系统无关的。
然后记得切换到指定tag
可以使用git tag命令得到,然后用git checkout命令切换,我这里使用的是1.20版本
之后直接执行make
之后将头文件拷贝到系统路径下:
sudo cp -r include/leveldb /usr/include
编译之后分别会得到out-shared和out-static两个文件夹,分别是动态库和静态库
我们进入out-shared文件夹,讲libleveldb.so*的三个文件(有两个是链接)拷贝到/usr/lib下
然后用sudo ldconfig 命令将动态库加到缓存中。
我们用如下代码测试一下:
1#include <iostream>
2#include <cassert>
3#include <cstdlib>
4#include <string>
5#include <leveldb/db.h>
6using namespace std;
7int main(void)
8{
9 leveldb::DB *db;
10 leveldb::Options options;
11 options.create_if_missing=true;
12 leveldb::Status status = leveldb::DB::Open(options,"./testdb",&db);
13 assert(status.ok());
14 std::string key1="people";
15 std::string value1="jason";
16 std::string value;
17 leveldb::Status s=db->Put(leveldb::WriteOptions(),key1,value1);
18 if(s.ok())
19 s=db->Get(leveldb::ReadOptions(),"people",&value);
20 if(s.ok())
21 cout<<value<<endl;
22 else
23 cout<<s.ToString()<<endl;
24 delete db;
25 return 0;
26}
编译选项为:
g++ mytest.cc -o mytest -lpthread -lleveldb
如果运行得到jason,表示安装成功。
LevelDB的使用
一些基本操作可以参考github文档
不过发现levelDB的接口似乎只支持key和value都是string类型。。
然而对于人脸提取feature,实际上需要的是string映射到float**
,偶然发现caffe中使用了levelDB,
发现它的做法是使用protobuf将数据序列化,然后再存储。
注意事项
记录一些踩坑的经历..
如果有100条数据,想要每10条存一个数据库,那么每10条执行一次DB::Open就行了…不然会报错在put那里,导致core dumped