Skip to main content
  1. Posts/

levelDB 使用笔记

·6 mins
Table of Contents
Note: This article is available in Chinese only. 本文暂无英文版本。 View original

2022-02-26 update:

说学习笔记听起来像在分析代码。。。但是实际上什么都没干,还是写"使用笔记"好了

大三的时候看过一点levelDB的源码,不过没有怎么用过。

最近有个需求是存人脸的feature到硬盘,似乎使用levelDB比较合适,因此来学习一下使用。

先放参考资料。

关于levelDB的语法,看这里就好了。

以及由于caffe中使用了levelDB,因此也可以参考下caffe源码。不过caffe中对levelDB的使用是又封装了一层。

具体可以参考:

  1#ifdef USE_LEVELDB
  2#ifndef CAFFE_UTIL_DB_LEVELDB_HPP
  3#define CAFFE_UTIL_DB_LEVELDB_HPP
  4
  5#include <string>
  6
  7#include "leveldb/db.h"
  8#include "leveldb/write_batch.h"
  9
 10#include "caffe/util/db.hpp"
 11
 12namespace caffe { namespace db {
 13
 14class LevelDBCursor : public Cursor {
 15 public:
 16  explicit LevelDBCursor(leveldb::Iterator* iter)
 17    : iter_(iter) {
 18    SeekToFirst();
 19    CHECK(iter_->status().ok()) << iter_->status().ToString();
 20  }
 21  ~LevelDBCursor() { delete iter_; }
 22  virtual void SeekToFirst() { iter_->SeekToFirst(); }
 23  virtual void Next() { iter_->Next(); }
 24  virtual string key() { return iter_->key().ToString(); }
 25  virtual string value() { return iter_->value().ToString(); }
 26  virtual bool valid() { return iter_->Valid(); }
 27
 28 private:
 29  leveldb::Iterator* iter_;
 30};
 31
 32class LevelDBTransaction : public Transaction {
 33 public:
 34  explicit LevelDBTransaction(leveldb::DB* db) : db_(db) { CHECK_NOTNULL(db_); }
 35  virtual void Put(const string& key, const string& value) {
 36    batch_.Put(key, value);
 37  }
 38  virtual void Commit() {
 39    leveldb::Status status = db_->Write(leveldb::WriteOptions(), &batch_);
 40    CHECK(status.ok()) << "Failed to write batch to leveldb "
 41                       << std::endl << status.ToString();
 42  }
 43
 44 private:
 45  leveldb::DB* db_;
 46  leveldb::WriteBatch batch_;
 47
 48  DISABLE_COPY_AND_ASSIGN(LevelDBTransaction);
 49};
 50
 51class LevelDB : public DB {
 52 public:
 53  LevelDB() : db_(NULL) { }
 54  virtual ~LevelDB() { Close(); }
 55  virtual void Open(const string& source, Mode mode);
 56  virtual void Close() {
 57    if (db_ != NULL) {
 58      delete db_;
 59      db_ = NULL;
 60    }
 61  }
 62  virtual LevelDBCursor* NewCursor() {
 63    return new LevelDBCursor(db_->NewIterator(leveldb::ReadOptions()));
 64  }
 65  virtual LevelDBTransaction* NewTransaction() {
 66    return new LevelDBTransaction(db_);
 67  }
 68
 69 private:
 70  leveldb::DB* db_;
 71};
 72
 73
 74}  // namespace db
 75}  // namespace caffe
 76
 77#endif  // CAFFE_UTIL_DB_LEVELDB_HPP
 78#endif  // USE_LEVELDB
 79
 80
 81
 82
 83
 84
 85#ifndef CAFFE_UTIL_DB_HPP
 86#define CAFFE_UTIL_DB_HPP
 87
 88#include <string>
 89
 90#include "caffe/common.hpp"
 91#include "caffe/proto/caffe.pb.h"
 92
 93namespace caffe { namespace db {
 94
 95enum Mode { READ, WRITE, NEW };
 96
 97class Cursor {
 98 public:
 99  Cursor() { }
100  virtual ~Cursor() { }
101  virtual void SeekToFirst() = 0;
102  virtual void Next() = 0;
103  virtual string key() = 0;
104  virtual string value() = 0;
105  virtual bool valid() = 0;
106
107  DISABLE_COPY_AND_ASSIGN(Cursor);
108};
109
110class Transaction {
111 public:
112  Transaction() { }
113  virtual ~Transaction() { }
114  virtual void Put(const string& key, const string& value) = 0;
115  virtual void Commit() = 0;
116
117  DISABLE_COPY_AND_ASSIGN(Transaction);
118};
119
120class DB {
121 public:
122  DB() { }
123  virtual ~DB() { }
124  virtual void Open(const string& source, Mode mode) = 0;
125  virtual void Close() = 0;
126  virtual Cursor* NewCursor() = 0;
127  virtual Transaction* NewTransaction() = 0;
128
129  DISABLE_COPY_AND_ASSIGN(DB);
130};
131
132DB* GetDB(DataParameter::DB backend);
133DB* GetDB(const string& backend);
134
135}  // namespace db
136}  // namespace caffe
137
138#endif  // CAFFE_UTIL_DB_HPP
139
140
141
142
143
144
145#ifdef USE_LEVELDB
146#include "caffe/util/db_leveldb.hpp"
147
148#include <string>
149
150namespace caffe { namespace db {
151
152void LevelDB::Open(const string& source, Mode mode) {
153  leveldb::Options options;
154  options.block_size = 65536;
155  options.write_buffer_size = 268435456;
156  options.max_open_files = 100;
157  options.error_if_exists = mode == NEW;
158  options.create_if_missing = mode != READ;
159  leveldb::Status status = leveldb::DB::Open(options, source, &db_);
160  CHECK(status.ok()) << "Failed to open leveldb " << source
161                     << std::endl << status.ToString();
162  LOG(INFO) << "Opened leveldb " << source;
163}
164
165}  // namespace db
166}  // namespace caffe
167#endif  // USE_LEVELDB
168
169
170
171
172
173
174#include "caffe/util/db.hpp"
175#include "caffe/util/db_leveldb.hpp"
176#include "caffe/util/db_lmdb.hpp"
177
178#include <string>
179
180namespace caffe { namespace db {
181
182DB* GetDB(DataParameter::DB backend) {
183  switch (backend) {
184#ifdef USE_LEVELDB
185  case DataParameter_DB_LEVELDB:
186    return new LevelDB();
187#endif  // USE_LEVELDB
188#ifdef USE_LMDB
189  case DataParameter_DB_LMDB:
190    return new LMDB();
191#endif  // USE_LMDB
192  default:
193    LOG(FATAL) << "Unknown database backend";
194    return NULL;
195  }
196}
197
198DB* GetDB(const string& backend) {
199#ifdef USE_LEVELDB
200  if (backend == "leveldb") {
201    return new LevelDB();
202  }
203#endif  // USE_LEVELDB
204#ifdef USE_LMDB
205  if (backend == "lmdb") {
206    return new LMDB();
207  }
208#endif  // USE_LMDB
209  LOG(FATAL) << "Unknown database backend";
210  return NULL;
211}
212
213}  // namespace db
214}  // namespace caffe
215
216
217
218
219
220// This program converts a set of images to a lmdb/leveldb by storing them
221// as Datum proto buffers.
222// Usage:
223//   convert_imageset [FLAGS] ROOTFOLDER/ LISTFILE DB_NAME
224//
225// where ROOTFOLDER is the root folder that holds all the images, and LISTFILE
226// should be a list of files as well as their labels, in the format as
227//   subfolder1/file1.JPEG 7
228//   ....
229
230#include <algorithm>
231#include <fstream>  // NOLINT(readability/streams)
232#include <string>
233#include <utility>
234#include <vector>
235
236#include "boost/scoped_ptr.hpp"
237#include "gflags/gflags.h"
238#include "glog/logging.h"
239
240#include "caffe/proto/caffe.pb.h"
241#include "caffe/util/db.hpp"
242#include "caffe/util/format.hpp"
243#include "caffe/util/io.hpp"
244#include "caffe/util/rng.hpp"
245
246using namespace caffe;  // NOLINT(build/namespaces)
247using std::pair;
248using boost::scoped_ptr;
249
250DEFINE_bool(gray, false,
251    "When this option is on, treat images as grayscale ones");
252DEFINE_bool(shuffle, false,
253    "Randomly shuffle the order of images and their labels");
254DEFINE_string(backend, "lmdb",
255        "The backend {lmdb, leveldb} for storing the result");
256DEFINE_int32(resize_width, 0, "Width images are resized to");
257DEFINE_int32(resize_height, 0, "Height images are resized to");
258DEFINE_bool(check_size, false,
259    "When this option is on, check that all the datum have the same size");
260DEFINE_bool(encoded, false,
261    "When this option is on, the encoded image will be save in datum");
262DEFINE_string(encode_type, "",
263    "Optional: What type should we encode the image as ('png','jpg',...).");
264
265int main(int argc, char** argv) {
266#ifdef USE_OPENCV
267  ::google::InitGoogleLogging(argv[0]);
268  // Print output to stderr (while still logging)
269  FLAGS_alsologtostderr = 1;
270
271#ifndef GFLAGS_GFLAGS_H_
272  namespace gflags = google;
273#endif
274
275  gflags::SetUsageMessage("Convert a set of images to the leveldb/lmdb\n"
276        "format used as input for Caffe.\n"
277        "Usage:\n"
278        "    convert_imageset [FLAGS] ROOTFOLDER/ LISTFILE DB_NAME\n"
279        "The ImageNet dataset for the training demo is at\n"
280        "    http://www.image-net.org/download-images\n");
281  gflags::ParseCommandLineFlags(&argc, &argv, true);
282
283  if (argc < 4) {
284    gflags::ShowUsageWithFlagsRestrict(argv[0], "tools/convert_imageset");
285    return 1;
286  }
287
288  const bool is_color = !FLAGS_gray;
289  const bool check_size = FLAGS_check_size;
290  const bool encoded = FLAGS_encoded;
291  const string encode_type = FLAGS_encode_type;
292
293  std::ifstream infile(argv[2]);
294  std::vector<std::pair<std::string, int> > lines;
295  std::string line;
296  size_t pos;
297  int label;
298  while (std::getline(infile, line)) {
299    pos = line.find_last_of(' ');
300    label = atoi(line.substr(pos + 1).c_str());
301    lines.push_back(std::make_pair(line.substr(0, pos), label));
302  }
303  if (FLAGS_shuffle) {
304    // randomly shuffle data
305    LOG(INFO) << "Shuffling data";
306    shuffle(lines.begin(), lines.end());
307  }
308  LOG(INFO) << "A total of " << lines.size() << " images.";
309
310  if (encode_type.size() && !encoded)
311    LOG(INFO) << "encode_type specified, assuming encoded=true.";
312
313  int resize_height = std::max<int>(0, FLAGS_resize_height);
314  int resize_width = std::max<int>(0, FLAGS_resize_width);
315
316  // Create new DB
317  scoped_ptr<db::DB> db(db::GetDB(FLAGS_backend));
318  db->Open(argv[3], db::NEW);
319  scoped_ptr<db::Transaction> txn(db->NewTransaction());
320
321  // Storing to db
322  std::string root_folder(argv[1]);
323  Datum datum;
324  int count = 0;
325  int data_size = 0;
326  bool data_size_initialized = false;
327
328  for (int line_id = 0; line_id < lines.size(); ++line_id) {
329    bool status;
330    std::string enc = encode_type;
331    if (encoded && !enc.size()) {
332      // Guess the encoding type from the file name
333      string fn = lines[line_id].first;
334      size_t p = fn.rfind('.');
335      if ( p == fn.npos )
336        LOG(WARNING) << "Failed to guess the encoding of '" << fn << "'";
337      enc = fn.substr(p+1);
338      std::transform(enc.begin(), enc.end(), enc.begin(), ::tolower);
339    }
340    status = ReadImageToDatum(root_folder + lines[line_id].first,
341        lines[line_id].second, resize_height, resize_width, is_color,
342        enc, &datum);
343    if (status == false) continue;
344    if (check_size) {
345      if (!data_size_initialized) {
346        data_size = datum.channels() * datum.height() * datum.width();
347        data_size_initialized = true;
348      } else {
349        const std::string& data = datum.data();
350        CHECK_EQ(data.size(), data_size) << "Incorrect data field size "
351            << data.size();
352      }
353    }
354    // sequential
355    string key_str = caffe::format_int(line_id, 8) + "_" + lines[line_id].first;
356
357    // Put in db
358    string out;
359    CHECK(datum.SerializeToString(&out));
360    txn->Put(key_str, out);
361
362    if (++count % 1000 == 0) {
363      // Commit db
364      txn->Commit();
365      txn.reset(db->NewTransaction());
366      LOG(INFO) << "Processed " << count << " files.";
367    }
368  }
369  // write the last batch
370  if (count % 1000 != 0) {
371    txn->Commit();
372    LOG(INFO) << "Processed " << count << " files.";
373  }
374#else
375  LOG(FATAL) << "This tool requires OpenCV; compile with USE_OPENCV.";
376#endif  // USE_OPENCV
377  return 0;
378}

几个文件。。。感觉比看文档更有实际意义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为例,但实际上除了路径可能不同,其他部分是系统无关的。

leveldb_github地址

然后记得切换到指定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将数据序列化,然后再存储。

protobuf学习笔记

注意事项
#

记录一些踩坑的经历..

如果有100条数据,想要每10条存一个数据库,那么每10条执行一次DB::Open就行了…不然会报错在put那里,导致core dumped

Related