-
Notifications
You must be signed in to change notification settings - Fork 0
/
search.go
90 lines (79 loc) · 1.51 KB
/
search.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
//go:build !plan9
package main
import (
"log"
"os"
"path"
"strings"
"sync"
"time"
"github.com/blevesearch/bleve/v2"
)
type textSearch struct {
index bleve.Index
sync.Mutex
}
func (t *textSearch) rescan() {
var err error
start := time.Now()
t.Lock()
t.index, err = bleve.NewMemOnly(bleve.NewIndexMapping())
if err != nil {
log.Fatal(err)
}
t.Unlock()
dir, err := os.ReadDir(path.Join(*rootDir, *postsDir))
if err != nil {
log.Fatal(err)
}
for _, f := range dir {
if f.IsDir() || !strings.HasSuffix(f.Name(), ".md") {
continue
}
t.add(f.Name())
}
log.Printf("txt: scan done in %v", time.Since(start))
}
func (t *textSearch) add(file string) {
file = path.Base(unescapeOrEmpty(file))
if file == "" {
return
}
b, err := os.ReadFile(path.Join(*rootDir, *postsDir, file))
if err != nil {
return
}
t.Lock()
defer t.Unlock()
t.index.Index(file, string(b))
log.Printf("txt: indexed %q", file)
}
func (t *textSearch) delete(file string) {
t.Lock()
defer t.Unlock()
t.index.Delete(path.Base(unescapeOrEmpty(file)))
}
func (t *textSearch) rename(old, new string) {
t.delete(old)
t.add(new)
}
func (t *textSearch) update(file string) {
t.delete(file)
t.add(file)
}
func (t *textSearch) search(query string) []string {
if query == "" {
return nil
}
t.Lock()
defer t.Unlock()
res, err := t.index.Search(bleve.NewSearchRequest(bleve.NewFuzzyQuery(query)))
if err != nil {
return nil
}
names := []string{}
for _, hit := range res.Hits {
names = append(names, hit.ID)
}
return names
}