-
Notifications
You must be signed in to change notification settings - Fork 0
/
fts.go
425 lines (395 loc) · 11.9 KB
/
fts.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
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
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
package v1
import (
"bytes"
"strconv"
"strings"
"unicode"
"unicode/utf8"
"github.com/clipperhouse/jargon"
"github.com/clipperhouse/jargon/filters/ascii"
"github.com/clipperhouse/jargon/filters/stemmer"
"github.com/doug-martin/goqu/v9/exp"
"github.com/ductone/protoc-gen-pgdb/internal/stackoverflow"
)
type SearchContent struct {
Type FieldOptions_FullTextType
Weight FieldOptions_FullTextWeight
Value interface{}
}
const minWordSize = 3
func interfaceToValue(in interface{}) string {
if in == nil {
return ""
}
switch v := in.(type) {
case bool:
return strconv.FormatBool(v)
case int32:
if v == 0 {
return ""
}
return strconv.FormatInt(int64(v), 10)
case int64:
if v == 0 {
return ""
}
return strconv.FormatInt(v, 10)
case uint32:
if v == 0 {
return ""
}
return strconv.FormatUint(uint64(v), 10)
case uint64:
if v == 0 {
return ""
}
return strconv.FormatUint(v, 10)
case string:
return v
case []string:
return strings.Join(v, " ")
default:
return ""
}
}
func lemmatizeDocs(docs []*SearchContent, additionalFilters ...jargon.Filter) []lexeme {
edgeGramFilter := edgegramStream(3)
filters := []jargon.Filter{lowerCaseFilter, ascii.Fold, stackoverflow.Tags}
filters = append(filters, additionalFilters...)
rv := make([]lexeme, 0, 8)
pos := 1
for _, doc := range docs {
docValue := interfaceToValue(doc.Value)
ts := jargon.TokenizeString(docValue).Filter(filters...)
for ts.Scan() {
// wrap around guard for position
if pos > 32767 {
pos = 1
}
token := ts.Token()
v := token.String()
if token.IsPunct() || token.IsSpace() {
pos += len(v)
continue
}
// always add the full word, without stemming (besides stackoverflow normalization)
rv = append(rv, lexeme{v, pos, doc.Weight})
switch doc.Type {
case FieldOptions_FULL_TEXT_TYPE_EXACT:
// no additional indexing for exact
case FieldOptions_FULL_TEXT_TYPE_ENGLISH, FieldOptions_FULL_TEXT_TYPE_UNSPECIFIED, FieldOptions_FULL_TEXT_TYPE_ENGLISH_LONG:
// for english, we also index "edge-grams" to make partial word matching work better.
if doc.Type != FieldOptions_FULL_TEXT_TYPE_ENGLISH_LONG {
grams, _ := jargon.TokenizeString(v).Filter(edgeGramFilter).Words().ToSlice()
gramWeight := lowerWeight(doc.Weight)
for _, gram := range grams {
rv = append(rv, lexeme{gram.String(), pos, gramWeight})
}
}
// we also apply stemming. yay?
stemmed, _ := jargon.TokenizeString(v).Filter(stemmer.English).Words().ToSlice()
for _, stemmedWord := range stemmed {
rv = append(rv, lexeme{stemmedWord.String(), pos, doc.Weight})
}
}
pos += len(v)
}
if err := ts.Err(); err != nil {
// we eat the error on purpose
_ = err
}
}
return rv
}
// snakeSubTokensSplitDoc tokenizes []string{bar, baz, quo} from foo_bar_baz quix_quo.
func snakeSubTokensSplitDoc(docValue string, wordBuffer bytes.Buffer, doc *SearchContent) []lexeme {
wordBuffer.Reset()
rv := make([]lexeme, 0, 8)
var pos = 1
var prev rune
for _, r := range docValue {
if prev == 0 {
prev = r
continue
}
if prev == '_' {
if wordBuffer.Len() == 0 { // no current word
if unicode.IsPunct(r) || unicode.IsSpace(r) || unicode.IsControl(r) || unicode.IsSymbol(r) {
prev = r
continue
}
// starting a new word
if _, e := wordBuffer.WriteRune(r); e != nil {
wordBuffer.Reset()
continue
}
}
} else if wordBuffer.Len() > 0 {
// in a current word, do we append or end?
switch {
case r == '_' || unicode.IsPunct(r) || unicode.IsSpace(r) || unicode.IsControl(r) || unicode.IsSymbol(r):
if utf8.RuneCount(wordBuffer.Bytes()) >= minWordSize {
// have a word, current is a rune that doesn't continue the word so end current word
rv = append(rv, lexeme{strings.ToLower(wordBuffer.String()), pos, doc.Weight})
}
wordBuffer.Reset()
default:
// in word and current rune continues word so continue appending
if _, e := wordBuffer.WriteRune(r); e != nil {
wordBuffer.Reset()
continue
}
}
}
prev = r
pos += 1
}
if utf8.RuneCount(wordBuffer.Bytes()) >= minWordSize {
rv = append(rv, lexeme{strings.ToLower(wordBuffer.String()), pos, doc.Weight})
}
return rv
}
// snakeFullTokensSplitDoc tokenizes []string{foobarbaz, quixquo} from foo_bar_baz quix_quo.
func snakeFullTokensSplitDoc(docValue string, wordBuffer bytes.Buffer, doc *SearchContent) []lexeme {
wordBuffer.Reset()
rv := make([]lexeme, 0, 8)
pos := 1
hasUnderscore := false
for _, r := range docValue {
if wordBuffer.Len() == 0 { // no current word
if r == '_' {
hasUnderscore = true
}
if unicode.IsPunct(r) || unicode.IsSpace(r) || unicode.IsControl(r) {
continue
}
// starting a new word
if _, e := wordBuffer.WriteRune(r); e != nil {
wordBuffer.Reset()
continue
}
} else if wordBuffer.Len() > 0 {
// in a current word, do we append or end?
switch {
case r != '_' && (unicode.IsPunct(r) || unicode.IsSpace(r) || unicode.IsControl(r)):
if hasUnderscore && utf8.RuneCount(wordBuffer.Bytes()) >= minWordSize {
// have a word, current is a rune that doesn't continue the word so end current word
rv = append(rv, lexeme{strings.ToLower(wordBuffer.String()), pos, doc.Weight})
}
hasUnderscore = false
wordBuffer.Reset()
default:
// in word and current rune continues word so continue appending
if r == '_' {
hasUnderscore = true
continue
}
if _, e := wordBuffer.WriteRune(r); e != nil {
wordBuffer.Reset()
hasUnderscore = false
continue
}
}
}
pos += 1
}
if hasUnderscore && utf8.RuneCount(wordBuffer.Bytes()) >= minWordSize {
rv = append(rv, lexeme{strings.ToLower(wordBuffer.String()), pos, doc.Weight})
}
return rv
}
func camelSplitDoc(docValue string, wordBuffer bytes.Buffer, doc *SearchContent) []lexeme {
wordBuffer.Reset()
rv := make([]lexeme, 0, 8)
var pos = 1
var prev rune
for _, r := range docValue {
if prev == 0 {
prev = r
continue
}
if unicode.IsUpper(prev) {
if wordBuffer.Len() == 0 { // no current word
if unicode.IsLower(r) {
// got a upper case in prev and current is lower, starting a new word
if _, e := wordBuffer.WriteRune(prev); e != nil {
wordBuffer.Reset()
continue
}
if _, e := wordBuffer.WriteRune(r); e != nil {
wordBuffer.Reset()
continue
}
}
}
} else if wordBuffer.Len() > 0 {
// in a current word, do we append or end?
switch {
case unicode.IsLower(r):
// in word and lower so continue appending
if _, e := wordBuffer.WriteRune(r); e != nil {
wordBuffer.Reset()
continue
}
case utf8.RuneCount(wordBuffer.Bytes()) >= minWordSize:
// have a word, current is not lower so end current word
rv = append(rv, lexeme{strings.ToLower(wordBuffer.String()), pos, doc.Weight})
wordBuffer.Reset()
default:
wordBuffer.Reset()
}
}
prev = r
pos += 1
}
if utf8.RuneCount(wordBuffer.Bytes()) >= minWordSize {
rv = append(rv, lexeme{strings.ToLower(wordBuffer.String()), pos, doc.Weight})
}
return rv
}
func acronymSplitDoc(docValue string, wordBuffer bytes.Buffer, doc *SearchContent) []lexeme {
wordBuffer.Reset()
rv := make([]lexeme, 0, 8)
var pos = 1
var prev rune
for _, r := range docValue {
if prev == 0 {
prev = r
continue
}
if unicode.IsUpper(prev) {
switch {
case unicode.IsLower(r):
// only append previous if it is upper case and and current is not lower case (i.e. don't append T in AWSTest).
if utf8.RuneCount(wordBuffer.Bytes()) >= minWordSize {
rv = append(rv, lexeme{strings.ToLower(wordBuffer.String()), pos, doc.Weight})
}
wordBuffer.Reset()
case !unicode.IsUpper(r):
// finish acronym if there is one of min length if we encounter space.
if _, e := wordBuffer.WriteRune(prev); e != nil {
wordBuffer.Reset()
continue
}
if utf8.RuneCount(wordBuffer.Bytes()) >= minWordSize {
rv = append(rv, lexeme{strings.ToLower(wordBuffer.String()), pos, doc.Weight})
}
wordBuffer.Reset()
default:
if _, e := wordBuffer.WriteRune(prev); e != nil {
wordBuffer.Reset()
continue
}
}
}
prev = r
pos += 1
}
// finish acronym if there is one of min length.
if wordBuffer.Len() > 0 {
if unicode.IsUpper(prev) {
if _, e := wordBuffer.WriteRune(prev); e != nil {
return rv
}
}
if utf8.RuneCount(wordBuffer.Bytes()) >= minWordSize {
rv = append(rv, lexeme{strings.ToLower(wordBuffer.String()), pos, doc.Weight})
}
}
return rv
}
// normalizeVectorDocs - converts a set of input documents into a set of lexemes matching common patterns such as camel case, snake case and accronyms.
func normalizeVectorDocs(docs []*SearchContent) []lexeme {
rv := make([]lexeme, 0, 8)
for _, doc := range docs {
if doc.Type == FieldOptions_FULL_TEXT_TYPE_ENGLISH_LONG {
continue
}
docValue := interfaceToValue(doc.Value)
var wordBuffer bytes.Buffer
rv = append(rv, camelSplitDoc(docValue, wordBuffer, doc)...)
rv = append(rv, snakeSubTokensSplitDoc(docValue, wordBuffer, doc)...)
rv = append(rv, snakeFullTokensSplitDoc(docValue, wordBuffer, doc)...)
rv = append(rv, acronymSplitDoc(docValue, wordBuffer, doc)...)
}
return rv
}
// FullTextSearchVectors converts a set of input documents
// into a ::tsvector. Note: this function may generally ignore errors in input text, to be robust to
// untrusted inputs, and will do its "best", for some value of "best".
func FullTextSearchVectors(docs []*SearchContent, additionalFilters ...jargon.Filter) exp.Expression {
rv := make([]lexeme, 0, 8)
rv = append(rv, lemmatizeDocs(docs, additionalFilters...)...)
rv = append(rv, normalizeVectorDocs(docs)...)
if len(rv) == 0 {
return exp.NewLiteralExpression("''::tsvector")
}
sb := strings.Builder{}
for _, v := range rv {
_, _ = sb.WriteString(pgLexeme(v.value, v.pos, v.weight))
_, _ = sb.WriteString(" ")
}
return exp.NewLiteralExpression("?::tsvector", sb.String())
}
func FullTextSearchQuery(input string, additionalFilters ...jargon.Filter) exp.Expression {
filters := []jargon.Filter{lowerCaseFilter, ascii.Fold, stackoverflow.Tags}
filters = append(filters, additionalFilters...)
jargon.TokenizeString(input)
terms, _ := jargon.TokenizeString(input).Filter(filters...).String()
stemmedTerms, _ := jargon.TokenizeString(input).Filter(stemmer.English).String()
terms = cleanToken(terms)
stemmedTerms = cleanToken(stemmedTerms)
return exp.NewLiteralExpression(
"(websearch_to_tsquery('simple', ?) || websearch_to_tsquery('simple', ?))",
terms, stemmedTerms)
}
type lexeme struct {
value string
pos int
weight FieldOptions_FullTextWeight
}
func cleanToken(in string) string {
rv := strings.Map(func(r rune) rune {
if unicode.IsDigit(r) || unicode.IsLetter(r) || unicode.IsSpace(r) {
return r
}
return specialReplaceChar
}, strings.ReplaceAll(in, "_", ""))
return rv
}
const specialReplaceChar = '�'
func pgLexeme(value string, pos int, weight FieldOptions_FullTextWeight) string {
value = cleanToken(value)
sb := strings.Builder{}
_, _ = sb.WriteString("'")
_, _ = sb.WriteString(value)
_, _ = sb.WriteString("'")
_, _ = sb.WriteString(":")
_, _ = sb.WriteString(strconv.FormatInt(int64(pos), 10))
_, _ = sb.WriteString(weightToString(weight))
return sb.String()
}
func weightToString(weight FieldOptions_FullTextWeight) string {
switch weight {
case FieldOptions_FULL_TEXT_WEIGHT_HIGH:
return "A"
case FieldOptions_FULL_TEXT_WEIGHT_MED:
return "B"
case FieldOptions_FULL_TEXT_WEIGHT_LOW:
return "C"
default:
return "D"
}
}
func lowerWeight(weight FieldOptions_FullTextWeight) FieldOptions_FullTextWeight {
switch weight {
case FieldOptions_FULL_TEXT_WEIGHT_HIGH:
return FieldOptions_FULL_TEXT_WEIGHT_MED
case FieldOptions_FULL_TEXT_WEIGHT_MED:
return FieldOptions_FULL_TEXT_WEIGHT_LOW
case FieldOptions_FULL_TEXT_WEIGHT_LOW:
return FieldOptions_FULL_TEXT_WEIGHT_UNSPECIFIED
default:
return FieldOptions_FULL_TEXT_WEIGHT_UNSPECIFIED
}
}