diff options
| author | alex <[email protected]> | 2026-07-28 17:37:06 +0200 |
|---|---|---|
| committer | alex <[email protected]> | 2026-07-28 17:37:06 +0200 |
| commit | c91c3afd8700138f8eb8a25a4ae422c2c9e46cea (patch) | |
| tree | fd9b5ea4f3b821581b2ceb4e7fa8afc1a84c0eeb /core/search | |
| parent | 5858d34b8ab573e18a4f6ddc5ee962b24ea269dc (diff) | |
| download | search-engine-c91c3afd8700138f8eb8a25a4ae422c2c9e46cea.tar.xz search-engine-c91c3afd8700138f8eb8a25a4ae422c2c9e46cea.zip | |
refactored entire code base to be in the package core so i can later implement interfaces to interact with the engine
Diffstat (limited to 'core/search')
| -rw-r--r-- | core/search/search.go | 72 |
1 files changed, 72 insertions, 0 deletions
diff --git a/core/search/search.go b/core/search/search.go new file mode 100644 index 0000000..e159d43 --- /dev/null +++ b/core/search/search.go @@ -0,0 +1,72 @@ +package search + +import ( + "searchEngine/core/analyzer" + "searchEngine/core/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 +} |
