forked from alash3al/libsrchx
-
Notifications
You must be signed in to change notification settings - Fork 0
/
store.go
82 lines (63 loc) · 1.57 KB
/
store.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package srchx
import (
"errors"
"os"
"path"
"path/filepath"
"strings"
"sync"
"github.com/blevesearch/bleve"
)
// Store our main store wrapper
type Store struct {
engine string
datapath string
indexes map[string]*Index
indexesLock sync.RWMutex
}
// NewStore initialize a new store using the specified engine & path, supported engines are (`badgerdb`, `leveldb`, `scorch`, `boltdb`)
func NewStore(engine, path string) (*Store, error) {
s := new(Store)
s.engine = "leveldb"
s.datapath = filepath.Join(path, s.engine)
s.indexes = map[string]*Index{}
s.indexesLock = sync.RWMutex{}
os.MkdirAll(s.datapath, 0744)
return s, nil
}
// GetIndex load/init an index and return it
func (s *Store) GetIndex(name string) (*Index, error) {
var err error
name = strings.ToLower(name)
ndx, ok := s.indexes[name]
if !ok {
ndx, err = s.InitIndex(name)
}
if err != nil {
return nil, err
}
return ndx, nil
}
// InitIndex create an index and register it in our main registry
func (s *Store) InitIndex(name string) (ndx *Index, err error) {
engine := "leveldb"
name = strings.ToLower(name)
indexPath := path.Join(s.datapath, name)
s.indexesLock.Lock()
defer s.indexesLock.Unlock()
if err = os.MkdirAll(indexPath, 0744); err != nil && err != os.ErrExist {
return nil, err
}
indexMapping := bleve.NewIndexMapping()
switch engine {
case "leveldb":
ndx, err = initLevelIndex(indexPath, indexMapping)
default:
err = errors.New("unknown engine (" + (engine) + ") specfied ")
}
if err != nil {
return nil, err
}
s.indexes[name] = ndx
return ndx, err
}