Last active
August 29, 2015 14:06
-
-
Save fyrz/374fe22fbac7f179cbcb to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <assert.h> | |
#include <string> | |
#include "rocksdb/db.h" | |
#include "rocksdb/comparator.h" | |
using namespace std; | |
using namespace rocksdb; | |
class ReverseKeyComparator : public rocksdb::Comparator { | |
public: | |
int Compare(const rocksdb::Slice& a, const rocksdb::Slice& b) const { | |
return -a.compare(b); | |
} | |
// Ignore the following methods for now: | |
const char* Name() const { return "ReverseKeyComparator"; } | |
void FindShortestSeparator(std::string*, const rocksdb::Slice&) const { } | |
void FindShortSuccessor(std::string*) const { } | |
}; | |
int main() { | |
DB* db; | |
Options options; | |
options.create_if_missing = true; | |
ReverseKeyComparator cmp; | |
options.comparator = &cmp; | |
// open a database with custom comparator | |
Status status = rocksdb::DB::Open(options, "/tmp/testdb", &db); | |
assert(status.ok()); | |
// populate the database | |
Slice key1 = "key1_2143214"; | |
Slice key2 = "key1_123214"; | |
Slice key3 = "key2_341434324"; | |
string val1 = "one"; | |
string val2 = "two"; | |
string val3 = "three"; | |
db->Put(WriteOptions(), key1, val1); | |
db->Put(WriteOptions(), key2, val2); | |
db->Put(WriteOptions(), key3, val3); | |
//iterate the database | |
auto it = db->NewIterator(rocksdb::ReadOptions()); | |
// Prefix initialization for seek operation | |
Slice prefix = "key1_33333"; | |
// Seek for first key1 ordered by numeric value in descending order | |
it->Seek(prefix); | |
if (it->Valid()){ | |
cout << it->key().ToString() << ": " << it->value().ToString() << endl; | |
} | |
cout << endl << endl; | |
// Iterate from first to last key/value pair in index | |
for (it->SeekToFirst(); it->Valid(); it->Next()) { | |
cout << it->key().ToString() << ": " << it->value().ToString() << endl; | |
} | |
// delete iterator | |
delete it; | |
// close the database | |
delete db; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment