-
Notifications
You must be signed in to change notification settings - Fork 1
/
fzfquery.go
57 lines (47 loc) · 1.33 KB
/
fzfquery.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
package search
import (
"context"
"github.com/blevesearch/bleve/v2/mapping"
"github.com/blevesearch/bleve/v2/search"
"github.com/blevesearch/bleve/v2/search/query"
"github.com/blevesearch/bleve/v2/search/searcher"
index "github.com/blevesearch/bleve_index_api"
"github.com/lithammer/fuzzysearch/fuzzy"
"math"
)
type fzfQuery struct {
s string
boost float64
}
func (q fzfQuery) Searcher(ctx context.Context, i index.IndexReader, m mapping.IndexMapping, options search.SearcherOptions) (search.Searcher, error) {
qBase := query.NewMatchAllQuery()
baseSearcher, err := qBase.Searcher(ctx, i, m, options)
if err != nil {
return nil, err
}
return searcher.NewFilteringSearcher(ctx, baseSearcher, func(d *search.DocumentMatch) bool {
doc, err := i.Document(string(d.IndexInternalID))
if err != nil || doc == nil {
return false
}
addr := ""
doc.VisitFields(func(field index.Field) {
if field.Name() == "addr" {
addr = string(field.Value())
}
})
if addr == "" {
return false
}
ld := fuzzy.RankMatchNormalizedFold(q.s, addr)
if ld < 0 {
return false
}
score := math.Min(1, math.Pow(2, -float64(ld)/float64(len(addr))))
d.Score = (d.Score + score*q.boost) / (q.boost + 1)
return true
}), nil
}
func newFzfQuery(s string, boost float64) query.Query {
return fzfQuery{s: s, boost: boost}
}