forked from HouzuoGuo/tiedot
/
col.go
233 lines (219 loc) · 6.28 KB
/
col.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
/* Collection schema and index management. */
package db
import (
"encoding/json"
"fmt"
"github.com/HouzuoGuo/tiedot/data"
"io/ioutil"
"os"
"path"
"strconv"
"strings"
)
const (
DOC_DATA_FILE = "dat_" // Prefix of partition collection data file name.
DOC_LOOKUP_FILE = "id_" // Prefix of partition hash table (ID lookup) file name.
INDEX_PATH_SEP = "!" // Separator between index keys in index directory name.
)
// Collection has data partitions and some index meta information.
type Col struct {
db *DB
name string
parts []*data.Partition // Collection partitions
hts []map[string]*data.HashTable // Index partitions
indexPaths map[string][]string // Index names and paths
}
// Open a collection and load all indexes.
func OpenCol(db *DB, name string) (*Col, error) {
col := &Col{db: db, name: name}
return col, col.load()
}
// Load collection schema including index schema.
func (col *Col) load() error {
if err := os.MkdirAll(path.Join(col.db.path, col.name), 0700); err != nil {
return err
}
col.parts = make([]*data.Partition, col.db.numParts)
col.hts = make([]map[string]*data.HashTable, col.db.numParts)
for i := 0; i < col.db.numParts; i++ {
col.hts[i] = make(map[string]*data.HashTable)
}
col.indexPaths = make(map[string][]string)
// Open collection document partitions
for i := 0; i < col.db.numParts; i++ {
var err error
if col.parts[i], err = data.OpenPartition(
path.Join(col.db.path, col.name, DOC_DATA_FILE+strconv.Itoa(i)),
path.Join(col.db.path, col.name, DOC_LOOKUP_FILE+strconv.Itoa(i))); err != nil {
return err
}
}
// Look for index directories
colDirContent, err := ioutil.ReadDir(path.Join(col.db.path, col.name))
if err != nil {
return err
}
for _, htDir := range colDirContent {
if !htDir.IsDir() {
continue
}
// Open index partitions
idxName := htDir.Name()
idxPath := strings.Split(idxName, INDEX_PATH_SEP)
col.indexPaths[idxName] = idxPath
for i := 0; i < col.db.numParts; i++ {
if col.hts[i] == nil {
col.hts[i] = make(map[string]*data.HashTable)
}
if col.hts[i][idxName], err = data.OpenHashTable(
path.Join(col.db.path, col.name, idxName, strconv.Itoa(i))); err != nil {
return err
}
}
}
return nil
}
// Close all collection files. Do not use the collection afterwards!
func (col *Col) close() error {
errs := make([]error, 0, 0)
for i := 0; i < col.db.numParts; i++ {
col.parts[i].Lock.Lock()
if err := col.parts[i].Close(); err != nil {
errs = append(errs, err)
}
for _, ht := range col.hts[i] {
if err := ht.Close(); err != nil {
errs = append(errs, err)
}
}
col.parts[i].Lock.Unlock()
}
if len(errs) == 0 {
return nil
}
return fmt.Errorf("%v", errs)
}
func (col *Col) forEachDoc(fun func(id int, doc []byte) (moveOn bool), placeSchemaLock bool) {
if placeSchemaLock {
col.db.schemaLock.RLock()
defer col.db.schemaLock.RUnlock()
}
// Process approx.4k documents in each iteration
partDiv := col.approxDocCount(false) / col.db.numParts / 4000
if partDiv == 0 {
partDiv++
}
for iteratePart := 0; iteratePart < col.db.numParts; iteratePart++ {
part := col.parts[iteratePart]
part.Lock.RLock()
for i := 0; i < partDiv; i++ {
if !part.ForEachDoc(i, partDiv, fun) {
part.Lock.RUnlock()
return
}
}
part.Lock.RUnlock()
}
}
// Do fun for all documents in the collection.
func (col *Col) ForEachDoc(fun func(id int, doc []byte) (moveOn bool)) {
col.forEachDoc(fun, true)
}
// Create an index on the path.
func (col *Col) Index(idxPath []string) (err error) {
col.db.schemaLock.Lock()
defer col.db.schemaLock.Unlock()
idxName := strings.Join(idxPath, INDEX_PATH_SEP)
if _, exists := col.indexPaths[idxName]; exists {
return fmt.Errorf("Path %v is already indexed", idxPath)
}
col.indexPaths[idxName] = idxPath
idxDir := path.Join(col.db.path, col.name, idxName)
if err = os.MkdirAll(idxDir, 0700); err != nil {
return err
}
for i := 0; i < col.db.numParts; i++ {
if col.hts[i][idxName], err = data.OpenHashTable(path.Join(idxDir, strconv.Itoa(i))); err != nil {
return err
}
}
// Put all documents on the new index
col.forEachDoc(func(id int, doc []byte) (moveOn bool) {
var docObj map[string]interface{}
if err := json.Unmarshal(doc, &docObj); err != nil {
// Skip corrupted document
return true
}
for _, idxVal := range GetIn(docObj, idxPath) {
if idxVal != nil {
hashKey := StrHash(fmt.Sprint(idxVal))
col.hts[hashKey%col.db.numParts][idxName].Put(hashKey, id)
}
}
return true
}, false)
return
}
// Return all indexed paths.
func (col *Col) AllIndexes() (ret [][]string) {
col.db.schemaLock.RLock()
defer col.db.schemaLock.RUnlock()
ret = make([][]string, 0, len(col.indexPaths))
for _, path := range col.indexPaths {
pathCopy := make([]string, len(path))
for i, p := range path {
pathCopy[i] = p
}
ret = append(ret, pathCopy)
}
return ret
}
// Remove an index.
func (col *Col) Unindex(idxPath []string) error {
col.db.schemaLock.Lock()
defer col.db.schemaLock.Unlock()
idxName := strings.Join(idxPath, INDEX_PATH_SEP)
if _, exists := col.indexPaths[idxName]; !exists {
return fmt.Errorf("Path %v is not indexed", idxPath)
}
delete(col.indexPaths, idxName)
for i := 0; i < col.db.numParts; i++ {
col.hts[i][idxName].Close()
delete(col.hts[i], idxName)
}
if err := os.RemoveAll(path.Join(col.db.path, col.name, idxName)); err != nil {
return err
}
return nil
}
func (col *Col) approxDocCount(placeSchemaLock bool) int {
if placeSchemaLock {
col.db.schemaLock.RLock()
defer col.db.schemaLock.RUnlock()
}
total := 0
for _, part := range col.parts {
part.Lock.RLock()
total += part.ApproxDocCount()
part.Lock.RUnlock()
}
return total
}
// Return approximate number of documents in the collection.
func (col *Col) ApproxDocCount() int {
return col.approxDocCount(true)
}
// Divide the collection into roughly equally sized pages, and do fun on all documents in the specified page.
func (col *Col) ForEachDocInPage(page, total int, fun func(id int, doc []byte) bool) {
col.db.schemaLock.RLock()
defer col.db.schemaLock.RUnlock()
for iteratePart := 0; iteratePart < col.db.numParts; iteratePart++ {
part := col.parts[iteratePart]
part.Lock.RLock()
if !part.ForEachDoc(page, total, fun) {
part.Lock.RUnlock()
return
}
part.Lock.RUnlock()
}
}