database/bitcask/bitcask_search.go

72 lines
1.7 KiB
Go
Raw Normal View History

2022-01-09 00:59:10 +00:00
package bitcask
2022-01-01 22:22:08 +00:00
import (
"strings"
)
2022-01-09 03:01:15 +00:00
// Search will search for a given string within all values inside of a Store.
// Note, type casting will be necessary. (e.g: []byte or string)
func (c Store) Search(query string) ([]KeyValue, error) {
var errs []error
var res []KeyValue
2022-01-01 22:22:08 +00:00
for _, key := range c.AllKeys() {
2022-01-09 03:01:15 +00:00
raw, err := c.Get(key)
if err != nil {
errs = append(errs, err)
}
2022-01-01 22:22:08 +00:00
if raw == nil {
continue
}
2022-01-09 03:01:15 +00:00
k := Key{b: key}
v := Value{b: raw}
2022-01-01 22:22:08 +00:00
if strings.Contains(string(raw), query) {
2022-01-09 03:01:15 +00:00
res = append(res, KeyValue{Key: k, Value: v})
2022-01-01 22:22:08 +00:00
}
}
2022-01-09 03:01:15 +00:00
return res, compoundErrors(errs)
2022-01-01 22:22:08 +00:00
}
2022-01-09 03:01:15 +00:00
// ValueExists will check for the existence of a Value anywhere within the keyspace, returning the Key and true if found, or nil and false if not found.
func (c Store) ValueExists(value []byte) (key []byte, ok bool) {
2022-01-01 22:22:08 +00:00
var raw []byte
2022-01-09 03:32:42 +00:00
var needle = Value{b:value}
2022-01-01 22:22:08 +00:00
for _, k := range c.AllKeys() {
2022-01-09 03:01:15 +00:00
raw, _ = c.Get(k)
2022-01-01 22:22:08 +00:00
if raw == nil {
continue
}
2022-01-09 03:32:42 +00:00
v := Value{b:raw}
if v.Equal(needle) {
2022-01-01 22:22:08 +00:00
ok = true
return
}
}
return
}
2022-01-09 03:01:15 +00:00
// PrefixScan will scan a Store for all keys that have a matching prefix of the given string
// and return a map of keys and values. (map[Key]Value)
func (c Store) PrefixScan(prefix string) (map[interface{}]Value, error) {
res := make(map[interface{}]Value)
err := c.Scan([]byte(prefix), func(key []byte) error {
2022-01-01 22:22:08 +00:00
raw, err := c.Get(key)
2022-01-09 03:01:15 +00:00
if err != nil {
2022-01-01 22:22:08 +00:00
return err
}
2022-01-09 03:01:15 +00:00
k := Key{b: key}
res[k] = Value{b: raw}
2022-01-01 22:22:08 +00:00
return nil
})
2022-01-09 03:01:15 +00:00
return res, err
2022-01-01 22:22:08 +00:00
}
2022-01-09 03:01:15 +00:00
// AllKeys will return all keys in the database as a slice of byte slices.
func (c Store) AllKeys() (keys [][]byte) {
2022-01-01 22:22:08 +00:00
keychan := c.Keys()
for key := range keychan {
2022-01-09 03:01:15 +00:00
keys = append(keys, key)
2022-01-01 22:22:08 +00:00
}
return
}