VC天下 » C/C++Linux

levelDB按时间范围检索

levelDB是谷歌的开源key-value存储系统,性能很高、设计思想很妙、使用起来也很简单。但像绝大多数的No Sql数据库一样,只适合做单一的查询,不能胜任复杂的关系组合查询。在实际项目中,我们应用levelDB,需要针对其进行一段时间的数据检索。于是,通过时间加减,来完成的这项功能,在此贴出简要代码,仅供参考。

先看数据插入的函数:

int InsertLevelDB(const char* key, const char* content)
{
//const char* Content = “2011-03-18   10:15:10,1.16591,2.27857,3.37197,4.45305,3.37197,1.16591,2.27857,3.37197,4.45305,5.52507,5.52507,4.45305,4.45305,4.45305,4.45305”;
leveldb::DB* db = NULL;
leveldb::Options options;
options.create_if_missing = true;
options.write_buffer_size = 8 * 1024* 1024;
leveldb::Status status = leveldb::DB::Open(options, “c:/tmp/testdb”, &db);

leveldb::WriteOptions wo;
wo.sync = false;
if (status.ok())
{
//    cout << “write key: ” << key << endl;
leveldb::Status s = db->Put(wo, key, content);
}
else
{
printf(“Insert LevelDB error\r\n”);
}
delete db;
return 0;
}

其中,key的形成,通过device_id+时间戳(time_t类型)

void GetKey(int device_id, time_t time_stamp, char* key)
{
char id[20];
_itoa_s(device_id, id, 10);
strcpy_s(key, 50, id);
char *timeStamp = TimeToChar(time_stamp); //自己实现的函数
strcat_s(key, 50, timeStamp);
}

根据时间起止点,检索数据,主要是time_t与struct tm的特性,通过时间的加减,形成key值,从而得到value值,存放到value集合中。

int QueryData(int device_id, time_t begin_time, time_t end_time, vector<string>& history_data)
{
leveldb::DB* db = NULL;
leveldb::Options options;
options.create_if_missing = true;
options.write_buffer_size = 8 * 1024* 1024;
leveldb::Status status = leveldb::DB::Open(options, “c:/tmp/testdb”, &db);
if (!status.ok())
{
delete db;
printf(“Insert LevelDB error\r\n”);
return -1;
}

time_t cur_time = begin_time ;
struct tm *beginTime, *curTime;
curTime = localtime(&begin_time);
char key[100];
string content;
while(cur_time <= end_time) //循环得到key,取出value
{
curTime->tm_sec += 1;
cur_time = mktime(curTime);
memset(key, 0, sizeof(key));
GetKey(device_id, cur_time, key);
leveldb::ReadOptions ro;
leveldb::Status s = db->Get(ro, key, &content);
if (!content.empty())
{
history_data.push_back(content.c_str());
}
}

delete db;
return 0;
}

One thought on “levelDB按时间范围检索

发表评论