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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
|
package index
import (
"bytes"
"context"
"encoding/gob"
"io/fs"
"log"
"log/slog"
"math"
"os"
"path"
"searchix/internal/file"
"searchix/internal/nix"
"slices"
"github.com/blevesearch/bleve/v2"
"github.com/blevesearch/bleve/v2/analysis/analyzer/custom"
"github.com/blevesearch/bleve/v2/analysis/analyzer/keyword"
"github.com/blevesearch/bleve/v2/analysis/analyzer/web"
"github.com/blevesearch/bleve/v2/analysis/token/camelcase"
"github.com/blevesearch/bleve/v2/analysis/tokenizer/letter"
"github.com/blevesearch/bleve/v2/analysis/tokenizer/single"
"github.com/blevesearch/bleve/v2/document"
"github.com/blevesearch/bleve/v2/mapping"
indexAPI "github.com/blevesearch/bleve_index_api"
"github.com/pkg/errors"
)
type WriteIndex struct {
index bleve.Index
Meta *Meta
}
type BatchError struct {
error
}
func (e *BatchError) Error() string {
return e.error.Error()
}
const batchSize = 10_000
func createIndexMapping() (mapping.IndexMapping, error) {
indexMapping := bleve.NewIndexMapping()
indexMapping.StoreDynamic = false
indexMapping.IndexDynamic = false
textFieldMapping := bleve.NewTextFieldMapping()
textFieldMapping.Store = false
descriptionFieldMapping := bleve.NewTextFieldMapping()
descriptionFieldMapping.Store = false
descriptionFieldMapping.Analyzer = web.Name
err := indexMapping.AddCustomAnalyzer("option_name", map[string]interface{}{
"type": custom.Name,
"tokenizer": letter.Name,
"token_filters": []string{
camelcase.Name,
},
})
if err != nil {
return nil, errors.WithMessage(err, "could not add custom analyser")
}
err = indexMapping.AddCustomAnalyzer("loc", map[string]interface{}{
"type": keyword.Name,
"tokenizer": letter.Name,
"token_filters": []string{
camelcase.Name,
},
})
if err != nil {
return nil, errors.WithMessage(err, "could not add custom analyser")
}
err = indexMapping.AddCustomAnalyzer("keyword_single", map[string]interface{}{
"type": keyword.Name,
"tokenizer": single.Name,
})
if err != nil {
return nil, errors.WithMessage(err, "could not add custom analyser")
}
keywordFieldMapping := bleve.NewKeywordFieldMapping()
keywordFieldMapping.Analyzer = "keyword_single"
nameMapping := bleve.NewTextFieldMapping()
nameMapping.Analyzer = "option_name"
nameMapping.IncludeTermVectors = true
nameMapping.Store = false
nixValueMapping := bleve.NewDocumentStaticMapping()
nixValueMapping.AddFieldMappingsAt("Text", textFieldMapping)
nixValueMapping.AddFieldMappingsAt("Markdown", textFieldMapping)
locFieldMapping := bleve.NewKeywordFieldMapping()
locFieldMapping.Analyzer = "loc"
locFieldMapping.IncludeTermVectors = true
locFieldMapping.Store = false
optionMapping := bleve.NewDocumentStaticMapping()
optionMapping.AddFieldMappingsAt("Name", keywordFieldMapping)
optionMapping.AddFieldMappingsAt("Source", keywordFieldMapping)
optionMapping.AddFieldMappingsAt("Loc", locFieldMapping)
optionMapping.AddFieldMappingsAt("RelatedPackages", textFieldMapping)
optionMapping.AddFieldMappingsAt("Description", textFieldMapping)
optionMapping.AddSubDocumentMapping("Default", nixValueMapping)
optionMapping.AddSubDocumentMapping("Example", nixValueMapping)
packageMapping := bleve.NewDocumentStaticMapping()
packageMapping.AddFieldMappingsAt("Attribute", keywordFieldMapping)
packageMapping.AddFieldMappingsAt("Source", keywordFieldMapping)
packageMapping.AddFieldMappingsAt("Description", textFieldMapping)
packageMapping.AddFieldMappingsAt("MainProgram", keywordFieldMapping)
packageMapping.AddFieldMappingsAt("PackageSet", keywordFieldMapping)
packageMapping.AddFieldMappingsAt("Platforms", keywordFieldMapping)
indexMapping.AddDocumentMapping("option", optionMapping)
indexMapping.AddDocumentMapping("package", packageMapping)
return indexMapping, nil
}
func createIndex(indexPath string) (bleve.Index, error) {
indexMapping, err := createIndexMapping()
if err != nil {
return nil, err
}
idx, err := bleve.NewUsing(
indexPath,
indexMapping,
bleve.Config.DefaultIndexType,
bleve.Config.DefaultKVStore,
map[string]interface{}{
"nosync": true,
},
)
if err != nil {
return nil, errors.WithMessagef(err, "unable to create index at path %s", indexPath)
}
return idx, nil
}
const (
indexBaseName = "index.bleve"
metaBaseName = "meta.json"
)
var expectedDataFiles = []string{
metaBaseName,
indexBaseName,
"sources",
}
func deleteIndex(dataRoot string) error {
dir, err := os.ReadDir(dataRoot)
if err != nil {
return errors.WithMessagef(err, "could not read data directory %s", dataRoot)
}
remainingFiles := slices.DeleteFunc(dir, func(e fs.DirEntry) bool {
return slices.Contains(expectedDataFiles, e.Name())
})
if len(remainingFiles) > 0 {
return errors.Errorf(
"cowardly refusing to remove data directory %s as it contains unknown files: %v",
dataRoot,
remainingFiles,
)
}
err = os.RemoveAll(dataRoot)
if err != nil {
return errors.WithMessagef(err, "could not remove data directory %s", dataRoot)
}
return nil
}
func OpenOrCreate(dataRoot string, force bool) (*ReadIndex, *WriteIndex, bool, error) {
var err error
bleve.SetLog(log.Default())
indexPath := path.Join(dataRoot, indexBaseName)
metaPath := path.Join(dataRoot, metaBaseName)
exists, err := file.Exists(indexPath)
if err != nil {
return nil, nil, exists, errors.WithMessagef(
err,
"could not check if index exists at path %s",
indexPath,
)
}
var idx bleve.Index
var meta *Meta
if !exists || force {
if force {
err = deleteIndex(dataRoot)
if err != nil {
return nil, nil, false, err
}
}
idx, err = createIndex(indexPath)
if err != nil {
return nil, nil, false, err
}
meta, err = createMeta(metaPath)
if err != nil {
return nil, nil, false, err
}
} else {
idx, err = bleve.Open(indexPath)
if err != nil {
return nil, nil, exists, errors.WithMessagef(err, "could not open index at path %s", indexPath)
}
meta, err = openMeta(metaPath)
if err != nil {
return nil, nil, exists, err
}
}
return &ReadIndex{
idx,
meta,
},
&WriteIndex{
idx,
meta,
},
exists,
nil
}
func (i *WriteIndex) SaveMeta() error {
return i.Meta.Save()
}
func (i *WriteIndex) Import(
ctx context.Context,
objects <-chan nix.Importable,
) <-chan error {
var err error
errs := make(chan error)
go func() {
defer close(errs)
k := 0
batch := i.index.NewBatch()
indexMapping := i.index.Mapping()
outer:
for obj := range objects {
select {
case <-ctx.Done():
slog.Warn("import aborted")
break outer
default:
}
doc := document.NewDocument(nix.GetKey(obj))
err = indexMapping.MapDocument(doc, obj)
if err != nil {
errs <- errors.WithMessagef(err, "could not map document for object: %s", obj.GetName())
continue
}
var data bytes.Buffer
enc := gob.NewEncoder(&data)
err = enc.Encode(&obj)
if err != nil {
errs <- errors.WithMessage(err, "could not store object in search index")
continue
}
field := document.NewTextFieldWithIndexingOptions("_data", nil, data.Bytes(), indexAPI.StoreField)
newDoc := doc.AddField(field)
// slog.Debug("adding object to index", "name", opt.Name)
err = batch.IndexAdvanced(newDoc)
if err != nil {
errs <- errors.WithMessagef(err, "could not index object %s", obj.GetName())
continue
}
if k++; k%batchSize == 0 {
err = i.Flush(batch)
if err != nil {
errs <- err
return
}
}
}
err := i.Flush(batch)
if err != nil {
errs <- err
}
}()
return errs
}
func (i *WriteIndex) Flush(batch *bleve.Batch) error {
size := batch.Size()
if size == 0 {
return &BatchError{
error: errors.New("no documents to flush"),
}
}
slog.Debug("flushing batch", "size", size)
err := i.index.Batch(batch)
if err != nil {
return &BatchError{
error: errors.WithMessagef(err, "could not flush batch"),
}
}
batch.Reset()
return nil
}
func (i *WriteIndex) Close() (err error) {
if e := i.Meta.Save(); e != nil {
// index needs to be closed anyway
err = errors.WithMessage(e, "could not save metadata")
}
if e := i.index.Close(); e != nil {
err = errors.WithMessagef(e, "could not close index")
}
return err
}
func (i *WriteIndex) DeleteBySource(source string) error {
query := bleve.NewTermQuery(source)
search := bleve.NewSearchRequest(query)
search.Size = math.MaxInt
search.Fields = []string{"_id"}
results, err := i.index.Search(search)
if err != nil {
return errors.WithMessagef(err, "failed to query documents of retired index %s", source)
}
batch := i.index.NewBatch()
var k uint
for _, hit := range results.Hits {
batch.Delete(hit.ID)
if k++; k%batchSize == 0 {
err := i.Flush(batch)
if err != nil {
return err
}
}
}
err = i.Flush(batch)
if err != nil {
return err
}
if uint64(search.Size) < results.Total {
return i.DeleteBySource(source) // unlikely :^)
}
return nil
}
|