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
|
package search
import (
"searchEngine/analyzer"
"searchEngine/index"
"slices"
)
type Result struct {
DocID int
Score int
}
func Search(idx *index.InvertedIndex, query string) []string {
tokenizedQuery := analyzer.ProcessText(query)
if len(tokenizedQuery) == 0 {
return nil
}
idx.Mu.RLock()
defer idx.Mu.RUnlock()
firstToken := tokenizedQuery[0]
basePostings, exists := idx.Data[firstToken]
if !exists {
return nil
}
scores := make(map[int]int)
for _, p := range basePostings {
scores[p.DocId] = p.BodyCount
}
for i := 1; i < len(tokenizedQuery); i++ {
token := tokenizedQuery[i]
nextPostings, exists := idx.Data[token]
if !exists {
return nil
}
lookup := make(map[int]int)
for _, p := range nextPostings {
lookup[p.DocId] = p.BodyCount
}
newScores := make(map[int]int)
for docID, currentScore := range scores {
if nextCount, found := lookup[docID]; found {
newScores[docID] = currentScore + nextCount
}
}
scores = newScores
}
var results []Result
for docID, score := range scores {
results = append(results, Result{DocID: docID, Score: score})
}
slices.SortFunc(results, func(a, b Result) int {
return b.Score - a.Score
})
var titles []string
for _, res := range results {
if title, exists := idx.DocNames[res.DocID]; exists {
titles = append(titles, title)
}
}
return titles
}
|