forked from Cloudxtreme/wiki-9
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsearch.go
92 lines (76 loc) · 1.81 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
package main
import (
"io/ioutil"
"log"
"os"
"path/filepath"
"strings"
"github.com/go-ego/riot/types"
)
// SearchHit - an individual search match
type SearchHit struct {
Title string
Page string
Subtext string
}
// SearchResults - container for results of searching
type SearchResults struct {
Term string
Hits []*SearchHit
Error error
}
func (s *Server) IndexPage(p *Page) {
s.searcher.Index(p.Title+FileExtension, types.DocData{Content: string(p.Body)})
s.searcher.Flush()
}
func (s *Server) SetupSearch() error {
docs := s.searcher.NumDocsIndexed()
log.Printf("index size: %+v", docs)
if docs > 0 {
return nil
}
log.Printf("scanning files: %+s", s.config.data)
err := filepath.Walk(s.config.data, func(fullFile string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if info.IsDir() && info.Name() == ".git" {
return filepath.SkipDir
}
if filepath.Ext(fullFile) == FileExtension {
rawData, err := ioutil.ReadFile(fullFile)
if err != nil {
return err
}
data := types.DocData{Content: string(rawData)}
relFile, err := filepath.Rel(s.config.data, fullFile)
if err != nil {
return err
}
log.Printf("indexing %s", relFile)
s.searcher.Index(relFile, data)
}
return nil
})
s.searcher.Flush()
log.Println("indexing done")
return err
}
func (s *Server) DoSearch(term string) *SearchResults {
results := &SearchResults{}
results.Term = term
results.Hits = make([]*SearchHit, 0)
sreq := types.SearchReq{Text: term}
sres := s.searcher.SearchDoc(sreq)
//log.Printf("results: %+v", sres)
for _, doc := range sres.Docs {
fullFile := doc.DocId
title := strings.TrimSuffix(fullFile, FileExtension)
hit := &SearchHit{
Title: title,
Page: "/view/" + title,
}
results.Hits = append(results.Hits, hit)
}
return results
}