summaryrefslogtreecommitdiff
path: root/core/index/index.go
blob: b00f5243ea6ee52cdbd0cd3666f8a0815112ab10 (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
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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
package index

import (
	"bufio"
	"encoding/gob"
	"os"
	"searchEngine/core/analyzer"
	"sync"
)

type Posting struct {
	DocId          int
	BodyPositions  []int
	TitlePositions []int
}

type InvertedIndex struct {
	Mu         sync.RWMutex `gob:"-"`
	Data       map[string][]Posting
	DocNames   map[int]string
	DocLengths map[int]int
}

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 {
		bodyPositions  []int
		titlePositions []int
	}
	docStats := make(map[string]fieldStats)

	for position, token := range titleTokens {
		stats := docStats[token]
		stats.titlePositions = append(stats.titlePositions, position)
		docStats[token] = stats
	}

	for position, token := range bodyTokens {
		stats := docStats[token]
		stats.bodyPositions = append(stats.bodyPositions, position)
		docStats[token] = stats
	}

	idx.Mu.Lock()
	defer idx.Mu.Unlock()

	idx.DocNames[docID] = title
	idx.DocLengths[docID] = len(bodyTokens)
	for token, stats := range docStats {
		idx.Data[token] = append(idx.Data[token], Posting{
			DocId:          docID,
			BodyPositions:  stats.bodyPositions,
			TitlePositions: stats.titlePositions,
		})
	}
}

func (idx *InvertedIndex) Save(filepath string) error {
	idx.Mu.RLock()
	defer idx.Mu.RUnlock()

	file, err := os.Create(filepath)
	if err != nil {
		return err
	}
	defer file.Close()

	writer := bufio.NewWriter(file)

	dto := struct {
		Data       map[string][]Posting
		DocNames   map[int]string
		DocLengths map[int]int
	}{
		Data:       idx.Data,
		DocNames:   idx.DocNames,
		DocLengths: idx.DocLengths,
	}

	encoder := gob.NewEncoder(writer)
	err = encoder.Encode(dto)

	if flushErr := writer.Flush(); flushErr != nil {
		return flushErr
	}
	return err
}

func Load(filepath string) (*InvertedIndex, error) {
	file, err := os.Open(filepath)
	if err != nil {
		return nil, err
	}
	defer file.Close()

	reader := bufio.NewReader(file)

	var dto struct {
		Data       map[string][]Posting
		DocNames   map[int]string
		DocLengths map[int]int
	}

	decoder := gob.NewDecoder(reader)
	err = decoder.Decode(&dto)
	if err != nil {
		return nil, err
	}

	return &InvertedIndex{
		Data:       dto.Data,
		DocNames:   dto.DocNames,
		DocLengths: dto.DocLengths,
	}, nil
}