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 <&lt; "write key: " &lt;&lt; key &lt;&lt; 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-&gt;Get(ro, key, &content);
        if (!content.empty())
        {
           history_data.push_back(content.c_str());
        }   
    }       

    delete db;
    return 0;
}

以上是大體思路,得益於key值中包含了時間,才得以實現的範圍檢索。 http://vcsky.net  by havenzhao

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章