Skip to content
Zohaib Sibte Hassan edited this page Mar 11, 2016 · 2 revisions

Iterators can be used to traverse over Key-Value pairs in the database. An iterator provides few basic functions:

  • void Seek(Slice key) to seek cursor to a given key
  • void SeekToFirst() to seek to first key in database
  • void SeekToLast() to seek to last key in database
  • void Next() move to next entry from current cursor position
  • void Prev() move to previous entry from current cursor position
  • bool Valid() returns true if the cursor is at a valid position, false otherwise
  • Slice Key() reads key slice from current cursor position
  • Slice Value() reads value slice from current cursor position

One can create a new cursor by calling DB.NewIterator(ReadOptions readOptions) method. Here is an example:

using (var itr = db.NewIterator(new ReadOptions()))
{
    itr.Seek(Slice.FromString("foo"));
    while (itr.Valid())
    {
        byte[] key = itr.Key().ToByteArray();
        byte[] val = itr.Value().ToByteArray();
        itr.Next();
    }
}

Iterators can be over a snapshot:

using (var snapshot = db.NewSnapshot())
using (var itr = db.NewIterator(new ReadOptions({ Snapshot = snapshot })))
{
  // use itr
}

An iterator can iterate in reverse order as well ?(Prev() method) but that is usually slower than forward iteration, so it's highly recommended avoid it as much as possible.

Clone this wiki locally