blob: cceabeb1500325f743c8f71fcec6561251293b22 (
plain)
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
|
package index
import (
"searchEngine/analyzer"
"sync"
)
type Posting struct {
DocId int
Count int
TitleCount int
}
type InvertedIndex struct {
Mu sync.RWMutex
Data map[string][]Posting
DocNames map[int]string
}
func New() *InvertedIndex {
return &InvertedIndex{
Data: make(map[string][]Posting),
DocNames: make(map[int]string),
}
}
func (idx *InvertedIndex) Add(docID int, title string, bodyTokens []string) {
titleTokens := analyzer.ProcessText(title)
type fieldStats struct {
body int
title int
}
docStats := make(map[string]fieldStats)
for _, token := range titleTokens {
stats := docStats[token]
stats.title++
docStats[token] = stats
}
for _, token := range bodyTokens {
stats := docStats[token]
stats.body++
docStats[token] = stats
}
idx.Mu.Lock()
defer idx.Mu.Unlock()
idx.DocNames[docID] = title
for token, stats := range docStats {
idx.Data[token] = append(idx.Data[token], Posting{
DocId: docID,
Count: stats.body,
TitleCount: stats.title,
})
}
}
|