我有一个巨大的csv文件数据库,大约有5M行,下面有字段
start_ip,end_ip,country,city,lat,long 我将它们存储在LevelDB中,使用start_ip作为键,rest作为值。
如何检索键的记录?
( ip_key > start_ip and ip_key < end_ip )任何替代解决方案。
发布于 2012-02-02 01:39:47
我假设您的键是IP的哈希值,哈希是64位的“无符号”整数,但如果不是这样,那么只需修改下面的代码来说明正确的键。
void MyClass::ReadRecordRange(const uint64 startRange, const uint64 endRange)
{
// Get the start slice and the end slice
leveldb::Slice startSlice(static_cast<const char*>(static_cast<const void*>(&startRange)), sizeof(startRange));
leveldb::Slice endSlice(static_cast<const char*>(static_cast<const void*>(&endRange)), sizeof(endRange));
// Get a database iterator
shared_ptr<leveldb::Iterator> dbIter(_database->NewIterator(leveldb::ReadOptions()));
// Possible optimization suggested by Google engineers
// for critical loops. Reduces memory thrash.
for(dbIter->Seek(startSlice); dbIter->Valid() && _options.comparator->Compare(dbIter->key(), endSlice)<=0); dbIter->Next())
{
// get the key
dbIter->key().data();
// get the value
dbIter->value().data();
// TODO do whatever you need to do with the key/value you read
}
}请注意,_options与您打开数据库实例时使用的leveldb::Options相同。您希望使用选项中指定的比较器,以便读取记录的顺序与数据库中的顺序相同。
如果您没有使用boost或tr1,那么您可以使用其他类似于shared_ptr的工具,也可以自己删除leveldb::Iterator。如果不删除迭代器,那么就会泄漏内存,并在调试模式下获得断言。
https://stackoverflow.com/questions/9097985
复制相似问题