Sorting by value in rocksdb

1.6k Views Asked by At

Rocksdb allows to sort the records by keys but I want to sort them by value. Is it possible to do that?

1

There are 1 best solutions below

0
On

RocksDB doesn't support secondary index directly, but you can build your own secondary index on top of RocksDB. Here is an very simple example using BatchWrite:

// create 2 ColumnFamily, one for data, one for index
Status s = db->CreateColumnFamily(cf_options, "Data", &data_handle);
Status s = db->CreateColumnFamily(cf_options, "Index", &index_handle);

// Use batch to guarantee consistency between data and index
WriteBatch batch;
batch.Put(data_handle, "key1", "value1");
batch.Put(index_handle, "value1", "key1");

db->Write(WriteOptions(), &batch);

std::string result;
s = db_->Get(ReadOptions(), data_handle, "key1", &result);
// index ColumnFamily is sorted by value
s = db_->Get(ReadOptions(), index_handle, "value1", &result);

This is an over simplified example, in reality you need to handle lots of other things like duplicated key or value, space amplification, etc. There're existing secondary-indices implementations for your reference, like: mokuroku, myrocks, etc.