levelDB按时间范围检索

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

http://vcsky.net  by havenzhao

先看数据插入的函数:

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; 
}


以上是大体思路,得益于key值中包含了时间,才得以实现的范围检索。 http://vcsky.net  by havenzhao

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值