I want the best performance code to get the last key value in the database. I google this problem and find SeekToLast function but I don't know how to use it.

1 Answers

0
Community On Best Solutions

Do you mean goleveldb?

If so then it will look like

iter := db.NewIterator(nil, nil)
ok := iter.Last()
if ok {
    key = iter.Key()
    value = iter.Value()
}
iter.Release() // Note: you should first get data and then release iterator
err = iter.Error()

Or to iterate from the end to the beginning.

iter := db.NewIterator(nil, nil)
for ok := iter.Last(); ok; ok = iter.Prev() {
    // Use key/value.
    // ...
}
iter.Release()
err = iter.Error()

You may also retrieve last key-value with specific prefix, or in general from some range (more details: https://godoc.org/github.com/syndtr/goleveldb/leveldb#DB.NewIterator)

iter := db.NewIterator(util.BytesPrefix([]byte("prefix_")), nil)
// or
iter := db.NewIterator(util.Range{
    Start: []byte("prefix_03"),
    Limit: []byte("prefix_04"),
}), nil)

Does it help?