boltdb / bolt

An embedded key/value database for Go.
MIT License
14.22k stars 1.51k forks source link

Can BoltDB support find all items whose name contains a pattern string? #619

Closed wolfxiaozhai closed 8 years ago

wolfxiaozhai commented 8 years ago

Did BoltDB support Regex when finding buckets or keys in one bucket? Here I gave my testing code.


package main

import (
    "fmt"
    "github.com/boltdb/bolt"
    "log"
)

var KVDB *bolt.DB

func main() {
    fmt.Println("start in main")
    KVDB, err := bolt.Open("my.db", 0600, nil)
    if err != nil {
        log.Fatal(err)
    }
    defer KVDB.Close()
    for i :=0;i<10;i++{
        KVDB.Update(func(tx *bolt.Tx) error {
            bucket_name := fmt.Sprintf("bucket%dbucket", i)
            fmt.Println(bucket_name)
            _, err := tx.CreateBucket([]byte(bucket_name))
            if err != nil {
                return fmt.Errorf("create bucket: %s", err)
            }
            return nil
        })
    }

    //I want to get bucket that contains one index like 1, 2, ...
    //Did boltDB support Regex????
    pattern := "1"
    err = KVDB.View(func(tx *bolt.Tx) error {
        bucket := tx.Bucket([]byte(pattern))
        if bucket == nil {
            return fmt.Errorf("bucket contains pattern %s not exist, the reason is\n", pattern)
        }
        return nil
    })
    if err != nil {
        fmt.Printf("Not exist\n")
    }
}
DavidVorick commented 8 years ago

Bolt does not support this natively, but you can iterate through all of the buckets/items yourself to see which ones match the pattern.

Bolt stores everything in sorted order as well. Sometimes you can overcome your need for fancier databases by choosing keys carefully, then doing a range over the keys between values X and Y.