-
Notifications
You must be signed in to change notification settings - Fork 0
/
search.go
108 lines (93 loc) · 2.42 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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
package service
import (
"encoding/json"
"fmt"
bolt "github.com/etcd-io/bbolt"
"github.com/peter-mount/go-kernel/v2/rest"
"github.com/peter-mount/nre-feeds/darwinref"
"sort"
"strings"
)
func newSearchResult(l *darwinref.Location, score, d float64) *darwinref.SearchResult {
var label = l.Name + " [" + l.Crs + "]"
if d > 0 {
label = fmt.Sprintf("%s [%s] %0.1fkm", l.Name, l.Crs, d)
} else {
label = fmt.Sprintf("%s [%s]", l.Name, l.Crs)
}
return &darwinref.SearchResult{
Crs: l.Crs,
Name: l.Name,
Label: label,
Score: score,
Distance: d,
}
}
func (dr *DarwinRefService) SearchName(term string) ([]*darwinref.SearchResult, error) {
if len(term) < 3 {
return nil, nil
}
term = strings.ToUpper(term)
set := make(map[string]*darwinref.SearchResult)
if err := dr.reference.View(func(tx *bolt.Tx) error {
crsBucket := tx.Bucket([]byte("DarwinCrs"))
tiplocBucket := tx.Bucket([]byte("DarwinTiploc"))
return crsBucket.ForEach(func(k, v []byte) error {
var tpls []string
err := json.Unmarshal(v, &tpls)
if err != nil {
return err
}
appendCrs := len(term) == 3 && string(k[:]) == term
for _, tpl := range tpls {
if loc, exists := dr.reference.GetTiplocBucket(tiplocBucket, tpl); exists {
var score float64
if appendCrs {
score = 1.0
} else {
s := strings.ToUpper(loc.Name)
if strings.Contains(s, term) {
score = float64(len(term)) / float64(len(s))
}
}
if score > 0.0 && loc.IsPublic() {
if _, exists := set[loc.Crs]; !exists {
set[loc.Crs] = newSearchResult(loc, score, 0.0)
}
}
}
}
return nil
})
}); err != nil {
return nil, err
}
// Get slice of values then sort by score descending
var result []*darwinref.SearchResult
for _, l := range set {
result = append(result, l)
}
sort.SliceStable(result, func(i, j int) bool {
// Compare scores at 2 decimal places
s1 := int32(100 * result[i].Score)
s2 := int32(100 * result[j].Score)
if s1 == s2 {
// Sort identical scores alphabetically
return strings.ToUpper(result[i].Name) < strings.ToUpper(result[j].Name)
} else {
// Sort scores by descending score order
return s1 > s2
}
})
return result, nil
}
func (dr *DarwinRefService) SearchHandler(r *rest.Rest) error {
if results, err := dr.SearchName(r.Var("term")); err != nil {
return err
} else {
r.Status(200).
JSON().
Value(results)
return nil
}
}