N P
N P

Reputation: 2619

Store and retrieve items in order using BoltDB

I am using BoltDB with Golang and want to store and then retrieve my items in the order they were placed into my database.

I am setting items using

func (r *Bolt) Set(key string, value []byte) error {
    return r.Client.Update(func(tx *bolt.Tx) error {
        b := tx.Bucket([]byte(r.bucket))
        return b.Put([]byte(key), value)
    })
}

And then I attempt to get all items and return the first 10 using a limit.

// GetAll will fetch the latest n record from Bolt, up to the limit supplied.
func (r *Bolt) GetAll(limit int) ([][]byte, error) {
    var results [][]byte

    if err := r.Client.View(func(tx *bolt.Tx) error {
        b := tx.Bucket([]byte(r.bucket))
        if b == nil {
            return fmt.Errorf("bucket %s not found", r.bucket)
        }

        // Set the cursor to the last key in the bucket
        c := b.Cursor()
        lastKey, _ := c.Last()

        // Iterate over the data in descending order, starting from the last key
        for k, v := c.Seek(lastKey); k != nil; k, v = c.Prev() {
            results = append(results, v)

            // Return if we have collected 50 items
            if len(results) >= limit {
                break
            }
        }

        return nil
    }); err != nil {
        return nil, err
    }

    return results, nil
}

If I use the following as keys test1, test2, test3, test4` in my database they always seem to be retrieved in random order.

Is there a way I can guarantee the order of items from BoltDB?

I have a createdAt time field on the data I'm saving, I'm thinking I could potentially use that but it would mean I'd have to retrieve all items and then sort.

Upvotes: 2

Views: 536

Answers (1)

You can. You are having the logical error in your code. You should use the c.First() method instead c.Seek() or c.Last() to do that according to documentation

Upvotes: 0

Related Questions