基本接口
Put/Get
使用key进行插入或查询
//opening a database leveldb::DB* db; leveldb::Options options; options.create_if_missing = true; leveldb::Status status = leveldb::DB::Open(options, "testdb", &db); assert(status.ok()); std::string key1="book"; std::string value1="algorithm"; std::string value; db->Put(WriteOptions(),key1,value1); db->Get(ReadOptions(),key1,&value); std::cout<<"key:"<<key1<<",value:"<<value<<std::endl;
Snapshot
可以查询历史版本的值,使用
readoptions
指定std::string key1="fruit"; std::string value1="apple"; status=db->Put(leveldb::WriteOptions(),key1,value1); assert(status.ok()); leveldb::ReadOptions readoptions; readoptions.snapshot=db->GetSnapshot(); std::string value2="orange"; status=db->Put(leveldb::WriteOptions(),key1,value2); assert(status.ok()); std::string value; //status=db->Get(leveldb::ReadOptions(),key1,&value); // snapshot status=db->Get(readoptions,key1,&value); assert(status.ok());
Writebatch
使用batch的方式进行写入,使用
WriteBatch
类进行write操作std::string key2="fruit"; std::string value2="apple"; if (status.ok()) { leveldb::WriteBatch batch; batch.Delete(key1); batch.Put(key2, value); status = db->Write(leveldb::WriteOptions(), &batch); }
练习
从文件读入数据并写入数据库(Batch)
std::string id, mail; std::ifstream inFile; leveldb::WriteBatch batch; inFile.open("/home/hadoop/Documents/data/PJ2/inputFile.csv"); if (status.ok()) { while (getline(inFile, id, ',')) { // std::cout << "ID: " << id << " "; getline(inFile, mail); // std::cout << "mail: " << mail << std::endl; batch.Put(id, mail); } } inFile.close(); // batch write status = db->Write(leveldb::WriteOptions(), &batch);
通过Get接口获取读入数据库的指定属性ID号和邮箱
int fibonacci[1000]; fibonacci[0] = 0; fibonacci[1] = 1; fibonacci[2] = 1; for (int i = 2; fibonacci[i-1] < 1000; i++) { fibonacci[i] = fibonacci[i - 1] + fibonacci[i - 2]; status = db->Get(leveldb::ReadOptions(), std::to_string(fibonacci[i-1]), &mail); assert(status.ok()); std::cout << fibonacci[i-1] << "\t" << mail << std::endl; }