buntdb icon indicating copy to clipboard operation
buntdb copied to clipboard

index, or getting with different keys doesn't work

Open marcelloh opened this issue 2 years ago • 1 comments

I have an index on "todo" and an index on "other" I have key "todo:00001" and a key "other:00001" when I save them and try to get only the "todo" ones (ascend the "todo" index) no record is found when I ascend the "other" index, I find the 2 records.

package main

import (
	"fmt"
	"log"
	"strings"

	"github.com/tidwall/buntdb"
)

const (
	todoBucket  = "todo"
	otherBucket = "other"
)

func main() {
	// Open the data.db file. It will be created if it doesn't exist.
	db, err := buntdb.Open("buntData.db")
	if err != nil {
		log.Fatal(err)
	}

	err = db.CreateIndex(todoBucket, todoBucket+":*", buntdb.IndexString)
	if err != nil && err.Error() != "index exists" {
		log.Println(strings.ReplaceAll(fmt.Sprintf(`save.go:97 err %#v`, err), `, `, ",\n"))
	}

	err = db.CreateIndex(otherBucket, otherBucket+":*", buntdb.IndexString)
	if err != nil && err.Error() != "index exists" {
		log.Println(strings.ReplaceAll(fmt.Sprintf(`save.go:97 err %#v`, err), `, `, ",\n"))
	}

	key := "0000000001"
	err = save(db, todoBucket, key)
	if err != nil {
		log.Println(strings.ReplaceAll(fmt.Sprintf(`save.go:107 err %#v`, err), `, `, ",\n"))
	}

	err = save(db, otherBucket, key)
	if err != nil {
		log.Println(strings.ReplaceAll(fmt.Sprintf(`save.go:107 err %#v`, err), `, `, ",\n"))
	}

	showAll(db, todoBucket)
	showAll(db, otherBucket)

	defer db.Close()
}

func save(db *buntdb.DB, bucket, key string) error {
	var err error
	dbkey := fmt.Sprintf("%s:%s", bucket, key)
	val := "val of key " + dbkey

	err = db.Update(func(tx *buntdb.Tx) error {
		log.Println(`save.go:103 key:`, dbkey)

		_, _, err = tx.Set(dbkey, val, nil)

		return err
	})

	return err
}

func showAll(db *buntdb.DB, bucket string) {
	var err error
	println("SHOWALL: " + bucket)

	err = db.View(
		func(tx *buntdb.Tx) error {
			err := tx.Ascend(bucket, func(key, value string) bool {
				fmt.Printf("key: %s, value: %s\n", key, value)
				return true // continue iteration
			})

			return err
		})

	log.Println(strings.ReplaceAll(fmt.Sprintf(`get.go:60 err %#v`, err), `, `, ",\n"))
}

marcelloh avatar May 11 '22 09:05 marcelloh

Idk what was wrong, start playing with it again, changed some stuff and it all worked out. (you can close this)

MarcelXia avatar Jun 07 '22 09:06 MarcelXia