This commit is contained in:
62
index.go
Normal file
62
index.go
Normal file
@@ -0,0 +1,62 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
|
||||
"github.com/blevesearch/bleve"
|
||||
)
|
||||
|
||||
// QuoteIndex index of quotes
|
||||
type QuoteIndex struct {
|
||||
index bleve.Index
|
||||
Videos []Quote
|
||||
videoByKey map[string]Quote //videoByKey[youtubeKey]
|
||||
}
|
||||
|
||||
// Search search quote in index
|
||||
func (si *QuoteIndex) Search(str string) ([]Quote, error) {
|
||||
var resp []Quote
|
||||
|
||||
query := bleve.NewMatchQuery(str)
|
||||
req := bleve.NewSearchRequest(query)
|
||||
searchResults, err := si.index.Search(req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("Request error %w", err)
|
||||
}
|
||||
for _, hit := range searchResults.Hits {
|
||||
if sound, ok := si.videoByKey[hit.ID]; ok {
|
||||
resp = append(resp, sound)
|
||||
}
|
||||
}
|
||||
|
||||
if len(resp) == 0 {
|
||||
return nil, fmt.Errorf("Quote not found")
|
||||
}
|
||||
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
func indexQuotes(quotes []Quote) (*QuoteIndex, error) {
|
||||
quoteMap := make(map[string]Quote)
|
||||
|
||||
mapping := bleve.NewIndexMapping()
|
||||
mapping.DefaultAnalyzer = mapping.FieldAnalyzer("french")
|
||||
index, err := bleve.NewMemOnly(mapping)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("Could not creat index: %w", err)
|
||||
}
|
||||
|
||||
for _, quote := range quotes {
|
||||
if index.Index(quote.YoutubeKey, quote.Quote) != nil {
|
||||
log.Printf("Error indexing %v\n", quote.Quote)
|
||||
}
|
||||
quoteMap[quote.YoutubeKey] = quote
|
||||
}
|
||||
|
||||
return &QuoteIndex{
|
||||
index,
|
||||
quotes,
|
||||
quoteMap,
|
||||
}, nil
|
||||
}
|
||||
Reference in New Issue
Block a user