SeekForPrev API

Start from 4.13, Rocksdb added Iterator::SeekForPrev(). This new API will seek to the last key that is less than or equal to the target key, in contrast with Seek().

  1. // Suppose we have keys "a1", "a3", "b1", "b2", "c2", "c4".
  2. auto iter = db->NewIterator(ReadOptions());
  3. iter->Seek("a1"); // iter->Key() == "a1";
  4. iter->Seek("a3"); // iter->Key() == "a3";
  5. iter->SeekForPrev("c4"); // iter->Key() == "c4";
  6. iter->SeekForPrev("c3"); // iter->Key() == "c2";

Basically, the behavior of SeekForPrev() is like the code snippet below:

  1. Seek(target);
  2. if (!Valid()) {
  3. SeekToLast();
  4. } else if (key() > target) {
  5. Prev();
  6. }

In fact, this API serves more than this code snippet. One typical example is, suppose we have keys, “a1”, “a3”, “a5”, “b1” and enable prefix_extractor which take the first byte as prefix. If we want to get the last key less than or equal to “a6”. The code above without SeekForPrev() doesn’t work. Since after Seek("a6") and Prev(), the iterator will enter the invalid state. But now, what you need is just a call, SeekForPrev("a6") and get “a5”.

Also, SeekForPrev() API serves internally to support Prev() in prefix mode. Now, Next() and Prev() could both be mixed in prefix mode. Thanks to SeekForPrev()!