-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindexer.go
196 lines (164 loc) · 5.14 KB
/
indexer.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
package minidoc
import (
"fmt"
"github.com/blevesearch/bleve"
_ "github.com/blevesearch/bleve/config"
"github.com/blevesearch/bleve/search/highlight/highlighter/ansi"
"strconv"
"strings"
//"github.com/blevesearch/bleve/search/highlight/format/ansi"
"github.com/blevesearch/bleve/analysis/analyzer/keyword"
"github.com/blevesearch/bleve/analysis/lang/en"
"github.com/blevesearch/bleve/mapping"
"github.com/blevesearch/bleve/search"
)
const (
ErrorGeneric Error = iota
ErrorCSVDoesNotExist
)
type Error int
func (e Error) Error() string {
return errorMessages[e]
}
var errorMessages = map[Error]string{
ErrorGeneric: "generic error",
ErrorCSVDoesNotExist: "cannot open csv, path does not exist",
}
type IndexHandler struct {
debug func(string)
index bleve.Index
indexPath string
}
type IndexHandlerOption func(*IndexHandler)
func WithIndexHandlerDebug(debug func(string)) IndexHandlerOption {
return func(ih *IndexHandler) {
ih.debug = debug
}
}
func WithIndexHandlerIndexPath(indexPath string) IndexHandlerOption {
return func(ih *IndexHandler) {
log.Debug("using index path: " + indexPath)
ih.indexPath = indexPath
}
}
const indexPathDefault = ".minidoc/index"
func NewIndexHandler(opts ...IndexHandlerOption) *IndexHandler {
ih := &IndexHandler{
indexPath: indexPathDefault,
debug: func(string) {},
}
for _, opt := range opts {
opt(ih)
}
index, err := bleve.Open(ih.indexPath)
if err == bleve.ErrorIndexPathDoesNotExist {
mapping, err := IndexMapping()
if err != nil {
log.Fatalf("error during loading index mapping: %v", err)
return nil
}
index, err = bleve.New(ih.indexPath, mapping)
if err != nil {
log.Fatalf("error during loading index: %v", err)
return nil
}
}
ih.index = index
log.Debug("index loaded successfully")
return ih
}
func (ih *IndexHandler) Delete(doc MiniDoc) error {
return ih.index.Delete(doc.GetIDString())
}
func (ih *IndexHandler) Index(doc MiniDoc) error {
return ih.index.Index(doc.GetIDString(), doc.GetJSON())
}
// indexCmd will index given csv file
func (ih *IndexHandler) Search(queryString string) ([]MiniDoc, string) {
log.Debug("index search")
// search for some text
query := bleve.NewMatchQuery(queryString)
search := &bleve.SearchRequest{
Query: query,
Size: 100,
From: 0,
Explain: false,
Sort: search.SortOrder{&search.SortScore{Desc: true}},
Fields: []string{"type", "title", "description", "tags"},
Highlight: bleve.NewHighlightWithStyle(ansi.Name),
}
sr, err := ih.index.Search(search)
if err != nil {
log.Errorf("index search error: %v", err)
return nil, ""
}
took := strings.ReplaceAll(sr.Took.String(), "µ", "u")
stat := fmt.Sprintf("%d matches, showing %d through %d, took %s", sr.Total, sr.Request.From+1, sr.Request.From+len(sr.Hits), took)
docs := make([]MiniDoc, sr.Hits.Len())
for ri, hit := range sr.Hits {
idparts := strings.Split(hit.ID, ":")
v, _ := strconv.Atoi(idparts[1])
log.Debugf("found minidoc[%d]", v)
minidoc := &BaseDoc{
ID: uint32(v),
}
if doctype, ok := hit.Fields["type"].(string); ok {
minidoc.Type = doctype
}
if title, ok := hit.Fields["title"].(string); ok {
minidoc.Title = title
}
if description, ok := hit.Fields["description"].(string); ok {
minidoc.Description = description
}
if tags, ok := hit.Fields["tags"].(string); ok {
minidoc.Tags = tags
}
log.Debug("# of fragments: " + strconv.Itoa(len(hit.Fragments)))
for fieldName, fragments := range hit.Fragments {
rv := "[" + fieldName + "[] "
for _, fragment := range fragments {
// [43m [0m
fragment = strings.ReplaceAll(fragment, "[43m", "[yellow]")
fragment = strings.ReplaceAll(fragment, "[0m", "[white]")
lines := strings.Split(fragment, "\n")
for _, line := range lines {
rv += fmt.Sprintf("%s ", line)
}
}
minidoc.Fragments = rv
}
docs[ri] = minidoc
log.Debugf("%s %f %s", hit.ID, hit.Score, hit.Fields["title"])
}
return docs, stat
}
func IndexMapping() (*mapping.IndexMappingImpl, error) {
// a generic reusable mapping for english text
englishTextFieldMapping := bleve.NewTextFieldMapping()
englishTextFieldMapping.Analyzer = en.AnalyzerName
// a generic reusable mapping for keyword text
keywordFieldMapping := bleve.NewTextFieldMapping()
keywordFieldMapping.Analyzer = keyword.Name
indexMapping := bleve.NewIndexMapping()
for _, doctype := range doctypes {
documentMapping := DocumentMapping(indexedFields[doctype], excludedFields[doctype])
indexMapping.AddDocumentMapping(doctype, documentMapping)
}
indexMapping.TypeField = "type"
indexMapping.DefaultAnalyzer = "en"
return indexMapping, nil
}
func DocumentMapping(indexedFields []string, excludedFields []string) *mapping.DocumentMapping {
englishTextFieldMapping := bleve.NewTextFieldMapping()
englishTextFieldMapping.Analyzer = en.AnalyzerName
documentMapping := bleve.NewDocumentMapping()
for _, f := range indexedFields {
documentMapping.AddFieldMappingsAt(f, englishTextFieldMapping)
}
disabledFieldMapping := bleve.NewDocumentDisabledMapping()
for _, f := range excludedFields {
documentMapping.AddSubDocumentMapping(f, disabledFieldMapping)
}
return documentMapping
}