请选择 进入手机版 | 继续访问电脑版
开启辅助访问
QQ登录|微信登录|登录 |立即注册

盖茨网区块链技术社区

leveldb数据库的基本用法

一、打开一个数据库实例一个leveldb数据库有一个对应一个文件系统目录的名字。该数据库的所有内容都存储在这个目录下。
下面的代码描述了怎样打开一个数据库或者建立一个新的数据库。
  1. #include <assert.h>   
  2. #include "leveldb/db.h"   
  3.      
  4. leveldb::DB* db;   
  5. leveldb::Options options;   
  6. options.create_if_missing = true;   
  7. leveldb::Status status = leveldb::DB::Open(options,"/tmp/testdb", &db);   
  8. assert(status.ok());
复制代码

如果打开已存在数据库的时候,需要抛出错误。将以下代码插在leveldb:B::Open方法前面:
  1. options.error_if_exists = true;
复制代码

二、对数据库的简单读、写操作LevelDB提供了Put,Delete和Get三个方法对数据库进行修改和查询。
例如,下面的代码片段描述了怎样将key1对应的value值,移到key2对应的值。std::string value;   
  1. leveldb::Status s = db->Get(leveldb::ReadOptions(), key1, &value);   
  2. if(s.ok()) s = db->Put(leveldb::WriteOptions(), key2, value);   
  3. if(s.ok()) s = db->Delete(leveldb::WriteOptions(), key1);
复制代码

三、关闭数据库在对数据库进行了一系列的操作之后,需要对数据库进行关闭。该操作比较简单:
... open the db as described above...   
... do something with db ...   
delete db;
上面对levelDB的简单使用做了基本的介绍,接下来就是如何自己写一个完成并且能运行的例子。

1、下载源码  git clone https://code.google.com/p/leveldb/
2、编译源码  cd leveldb && make all
3、编写                 test.cpp
  1. #include <assert.h>   
  2. #include <string.h>   
  3. #include <leveldb/db.h>   
  4. #include <iostream>   
  5.      
  6. int main(){   
  7.         leveldb::DB* db;   
  8.         leveldb::Options options;   
  9.         options.create_if_missing = true;   
  10.         leveldb::Status status = leveldb::DB::Open(options,"/tmp/testdb", &db);   
  11.         assert(status.ok());   
  12.      
  13.         //write key1,value1   
  14.         std::string key="key";   
  15.         std::string value = "value";   
  16.      
  17.         status = db->Put(leveldb::WriteOptions(), key,value);   
  18.         assert(status.ok());   
  19.      
  20.         status = db->Get(leveldb::ReadOptions(), key, &value);   
  21.         assert(status.ok());   
  22.         std::cout<<value<<std::endl;   
  23.         std::string key2 = "key2";   
  24.             
  25.         //move the value under key to key2   
  26.             
  27.         status = db->Put(leveldb::WriteOptions(),key2,value);   
  28.         assert(status.ok());   
  29.         status = db->Delete(leveldb::WriteOptions(), key);   
  30.      
  31.         assert(status.ok());   
  32.             
  33.         status = db->Get(leveldb::ReadOptions(),key2, &value);   
  34.             
  35.         assert(status.ok());   
  36.         std::cout<<key2<<"==="<<value<<std::endl;   
  37.             
  38.         status = db->Get(leveldb::ReadOptions(),key, &value);   
  39.             
  40.         if(!status.ok()) std::cerr<<key<<"    "<<status.ToString()<<std::endl;   
  41.         else std::cout<<key<<"==="<<value<<std::endl;   
  42.             
  43.         delete db;   
  44.         return 0;   
  45. }
复制代码
4、编译链接 g++ -o test test.cpp ../leveldb/libleveldb.a -lpthread -I../leveldb/include     
注意libleveldb.a 和leveldb include的路径。
5、运行结果./test:value   
key2===value   
key    NotFound:

============同步操作=================
  1. leveldb::WriteOptions write_options;设置读写操作选项
  2. write_options.sync = true;开启同步
  3. db->Put(write_options, ...);
复制代码
===========迭代器,遍历所有kv================
  1. leveldb::Iterator* it = db->NewIterator(leveldb::ReadOptions());
  2. for (it->SeekToFirst(); it->Valid(); it->Next()) {
  3.   cout << it->key().ToString() << ": "  << it->value().ToString() << endl;
  4. }
  5. assert(it->status().ok());  // Check for any errors found during the scan
  6. delete it;
复制代码

============BatchWrite用法==============
BatchWrite是一个批写入类
获取BatchWrite是通过DB类的createWriteBatch方法,BatchWrite使用中就只有两个用法,put和delete
  1. String path = "/data/leveldb";
  2. DBFactory factory = new Iq80DBFactory();
  3. Options options = new Options();
  4. options.createIfMissing(true);
  5. DB db = factory.open(new File(path), options);

  6. WriteBatch writeBatch = db.createWriteBatch();
  7. writeBatch.put(bytes("key1"), bytes("value1"));
  8. db.get(bytes("key1"));

  9. writeBatch.put(bytes("key2"), bytes("value2"));

  10. db.write(writeBatch);
复制代码
BatchWrite也就是批量写入,在以上两个put操作中,还进行了一次取value的操作,然后最后进行一次性批量写入
附录:
  1. class Slice {
  2. public:
  3.   // Create an empty slice.
  4.   Slice() : data_(""), size_(0) { }

  5.   // Create a slice that refers to d[0,n-1].
  6.   Slice(const char* d, size_t n) : data_(d), size_(n) { }

  7.   // Create a slice that refers to the contents of "s"
  8.   Slice(const std::string& s) : data_(s.data()), size_(s.size()) { }

  9.   // Create a slice that refers to s[0,strlen(s)-1]
  10.   Slice(const char* s) : data_(s), size_(strlen(s)) { }

  11.   // Return a pointer to the beginning of the referenced data
  12.   const char* data() const { return data_; }

  13.   // Return the length (in bytes) of the referenced data
  14.   size_t size() const { return size_; }

  15.   // Return true iff the length of the referenced data is zero
  16.   bool empty() const { return size_ == 0; }

  17.   // Return the ith byte in the referenced data.
  18.   // REQUIRES: n < size()
  19.   char operator[](size_t n) const {
  20.     assert(n < size());
  21.     return data_[n];
  22.   }

  23.   // Change this slice to refer to an empty array
  24.   void clear() { data_ = ""; size_ = 0; }

  25.   // Drop the first "n" bytes from this slice.
  26.   void remove_prefix(size_t n) {
  27.     assert(n <= size());
  28.     data_ += n;
  29.     size_ -= n;
  30.   }

  31.   // Return a string that contains the copy of the referenced data.
  32.   std::string ToString() const { return std::string(data_, size_); }

  33.   // Three-way comparison.  Returns value:
  34.   //   <  0 iff "*this" <  "b",
  35.   //   == 0 iff "*this" == "b",
  36.   //   >  0 iff "*this" >  "b"
  37.   int compare(const Slice& b) const;

  38.   // Return true iff "x" is a prefix of "*this"
  39.   bool starts_with(const Slice& x) const {
  40.     return ((size_ >= x.size_) &&
  41.             (memcmp(data_, x.data_, x.size_) == 0));
  42.   }

  43. private:
  44.   const char* data_;
  45.   size_t size_;

  46.   // Intentionally copyable
  47. };
复制代码
leveldb所有操作的单元均为Slice


  1. class DB {
  2. public:
  3.   // Open the database with the specified "name".
  4.   // Stores a pointer to a heap-allocated database in *dbptr and returns
  5.   // OK on success.
  6.   // Stores NULL in *dbptr and returns a non-OK status on error.
  7.   // Caller should delete *dbptr when it is no longer needed.
  8.   static Status Open(const Options& options,
  9.                      const std::string& name,
  10.                      DB** dbptr);

  11.   DB() { }
  12.   virtual ~DB();

  13.   // Set the database entry for "key" to "value".  Returns OK on success,
  14.   // and a non-OK status on error.
  15.   // Note: consider setting options.sync = true.
  16.   virtual Status Put(const WriteOptions& options,
  17.                      const Slice& key,
  18.                      const Slice& value) = 0;

  19.   // Remove the database entry (if any) for "key".  Returns OK on
  20.   // success, and a non-OK status on error.  It is not an error if "key"
  21.   // did not exist in the database.
  22.   // Note: consider setting options.sync = true.
  23.   virtual Status Delete(const WriteOptions& options, const Slice& key) = 0;

  24.   // Apply the specified updates to the database.
  25.   // Returns OK on success, non-OK on failure.
  26.   // Note: consider setting options.sync = true.
  27.   virtual Status Write(const WriteOptions& options, WriteBatch* updates) = 0;

  28.   // If the database contains an entry for "key" store the
  29.   // corresponding value in *value and return OK.
  30.   //
  31.   // If there is no entry for "key" leave *value unchanged and return
  32.   // a status for which Status::IsNotFound() returns true.
  33.   //
  34.   // May return some other Status on an error.
  35.   virtual Status Get(const ReadOptions& options,
  36.                      const Slice& key, std::string* value) = 0;

  37.   // Return a heap-allocated iterator over the contents of the database.
  38.   // The result of NewIterator() is initially invalid (caller must
  39.   // call one of the Seek methods on the iterator before using it).
  40.   //
  41.   // Caller should delete the iterator when it is no longer needed.
  42.   // The returned iterator should be deleted before this db is deleted.
  43.   virtual Iterator* NewIterator(const ReadOptions& options) = 0;

  44.   // Return a handle to the current DB state.  Iterators created with
  45.   // this handle will all observe a stable snapshot of the current DB
  46.   // state.  The caller must call ReleaseSnapshot(result) when the
  47.   // snapshot is no longer needed.
  48.   virtual const Snapshot* GetSnapshot() = 0;

  49.   // Release a previously acquired snapshot.  The caller must not
  50.   // use "snapshot" after this call.
  51.   virtual void ReleaseSnapshot(const Snapshot* snapshot) = 0;

  52.   // DB implementations can export properties about their state
  53.   // via this method.  If "property" is a valid property understood by this
  54.   // DB implementation, fills "*value" with its current value and returns
  55.   // true.  Otherwise returns false.
  56.   //
  57.   //
  58.   // Valid property names include:
  59.   //
  60.   //  "leveldb.num-files-at-level<N>" - return the number of files at level <N>,
  61.   //     where <N> is an ASCII representation of a level number (e.g. "0").
  62.   //  "leveldb.stats" - returns a multi-line string that describes statistics
  63.   //     about the internal operation of the DB.
  64.   //  "leveldb.sstables" - returns a multi-line string that describes all
  65.   //     of the sstables that make up the db contents.
  66.   virtual bool GetProperty(const Slice& property, std::string* value) = 0;

  67.   // For each i in [0,n-1], store in "sizes[i]", the approximate
  68.   // file system space used by keys in "[range[i].start .. range[i].limit)".
  69.   //
  70.   // Note that the returned sizes measure file system space usage, so
  71.   // if the user data compresses by a factor of ten, the returned
  72.   // sizes will be one-tenth the size of the corresponding user data size.
  73.   //
  74.   // The results may not include the sizes of recently written data.
  75.   virtual void GetApproximateSizes(const Range* range, int n,
  76.                                    uint64_t* sizes) = 0;

  77.   // Compact the underlying storage for the key range [*begin,*end].
  78.   // In particular, deleted and overwritten versions are discarded,
  79.   // and the data is rearranged to reduce the cost of operations
  80.   // needed to access the data.  This operation should typically only
  81.   // be invoked by users who understand the underlying implementation.
  82.   //
  83.   // begin==NULL is treated as a key before all keys in the database.
  84.   // end==NULL is treated as a key after all keys in the database.
  85.   // Therefore the following call will compact the entire database:
  86.   //    db->CompactRange(NULL, NULL);
  87.   virtual void CompactRange(const Slice* begin, const Slice* end) = 0;

  88. private:
  89.   // No copying allowed
  90.   DB(const DB&);
  91.   void operator=(const DB&);
  92. };
复制代码
以上为db类的描述,其中可以通过Iterator* NewIterator(const ReadOptions& options)得到迭代器遍历数据库。

  1. class Iterator {
  2. public:
  3.   Iterator();
  4.   virtual ~Iterator();

  5.   // An iterator is either positioned at a key/value pair, or
  6.   // not valid.  This method returns true iff the iterator is valid.
  7.   virtual bool Valid() const = 0;

  8.   // Position at the first key in the source.  The iterator is Valid()
  9.   // after this call iff the source is not empty.
  10.   virtual void SeekToFirst() = 0;

  11.   // Position at the last key in the source.  The iterator is
  12.   // Valid() after this call iff the source is not empty.
  13.   virtual void SeekToLast() = 0;

  14.   // Position at the first key in the source that at or past target
  15.   // The iterator is Valid() after this call iff the source contains
  16.   // an entry that comes at or past target.
  17.   virtual void Seek(const Slice& target) = 0;

  18.   // Moves to the next entry in the source.  After this call, Valid() is
  19.   // true iff the iterator was not positioned at the last entry in the source.
  20.   // REQUIRES: Valid()
  21.   virtual void Next() = 0;

  22.   // Moves to the previous entry in the source.  After this call, Valid() is
  23.   // true iff the iterator was not positioned at the first entry in source.
  24.   // REQUIRES: Valid()
  25.   virtual void Prev() = 0;

  26.   // Return the key for the current entry.  The underlying storage for
  27.   // the returned slice is valid only until the next modification of
  28.   // the iterator.
  29.   // REQUIRES: Valid()
  30.   virtual Slice key() const = 0;

  31.   // Return the value for the current entry.  The underlying storage for
  32.   // the returned slice is valid only until the next modification of
  33.   // the iterator.
  34.   // REQUIRES: Valid()
  35.   virtual Slice value() const = 0;

  36.   // If an error has occurred, return it.  Else return an ok status.
  37.   virtual Status status() const = 0;

  38.   // Clients are allowed to register function/arg1/arg2 triples that
  39.   // will be invoked when this iterator is destroyed.
  40.   //
  41.   // Note that unlike all of the preceding methods, this method is
  42.   // not abstract and therefore clients should not override it.
  43.   typedef void (*CleanupFunction)(void* arg1, void* arg2);
  44.   void RegisterCleanup(CleanupFunction function, void* arg1, void* arg2);

  45. private:
  46.   struct Cleanup {
  47.     CleanupFunction function;
  48.     void* arg1;
  49.     void* arg2;
  50.     Cleanup* next;
  51.   };
  52.   Cleanup cleanup_;

  53.   // No copying allowed
  54.   Iterator(const Iterator&);
  55.   void operator=(const Iterator&);
  56. };
复制代码
迭代器描述





0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则