You can have a look at examples in txn_test.go
Here is an example code:
func TestReverse(t *testing.T) {
dir, err := ioutil.TempDir("", "badger-test")
require.NoError(t, err)
defer os.RemoveAll(dir)
ops := getTestOptions(dir).WithNumVersionsToKeep(math.MaxInt32)
db, err := Open(ops)
require.NoError(t, err)
for i := 0; i < 10; i++ {
require.NoError(t, db.Update(func(txn *Txn) error {
require.NoError(t, txn.Set([]byte("key"), []byte(fmt.Sprintf("%05d", i))))
return nil
}))
}
fmt.Println("Reverse")
require.NoError(t, db.View(func(txn *Txn) error {
iopts := DefaultIteratorOptions
iopts.Reverse = true
iopts.AllVersions = true
iopts.Prefix = []byte("key")
it := txn.NewIterator(iopts)
defer it.Close()
for it.Rewind(); it.ValidForPrefix(iopts.Prefix); it.Next() {
x, _ := it.Item().ValueCopy(nil)
fmt.Printf("%+v value:%s\n", it.Item(), x)
}
return nil
}))
fmt.Println("No reverse")
require.NoError(t, db.View(func(txn *Txn) error {
iopts := DefaultIteratorOptions
iopts.Reverse = false
iopts.AllVersions = true
iopts.Prefix = []byte("key")
it := txn.NewIterator(iopts)
defer it.Close()
for it.Rewind(); it.ValidForPrefix(iopts.Prefix); it.Next() {
x, _ := it.Item().ValueCopy(nil)
fmt.Printf("%+v value:%s\n", it.Item(), x)
}
return nil
}))
require.NoError(t, db.Close())
}
It outputs:
Reverse
key="key", version=1, meta=40 value:00000
key="key", version=2, meta=40 value:00001
key="key", version=3, meta=40 value:00002
key="key", version=4, meta=40 value:00003
key="key", version=5, meta=40 value:00004
key="key", version=6, meta=40 value:00005
key="key", version=7, meta=40 value:00006
key="key", version=8, meta=40 value:00007
key="key", version=9, meta=40 value:00008
key="key", version=10, meta=40 value:00009
No reverse
key="key", version=10, meta=40 value:00009
key="key", version=9, meta=40 value:00008
key="key", version=8, meta=40 value:00007
key="key", version=7, meta=40 value:00006
key="key", version=6, meta=40 value:00005
key="key", version=5, meta=40 value:00004
key="key", version=4, meta=40 value:00003
key="key", version=3, meta=40 value:00002
key="key", version=2, meta=40 value:00001
key="key", version=1, meta=40 value:00000