package main
import (
"fmt"
"strings"
)
func main() {
// 正排索引
words := []string{"world", "hello jack", "hello marry"}
// search content contains "hello"
for i, word := range words {
if strings.Contains(word, "hello") {
fmt.Println(i, word)
}
}
fmt.Println()
// 倒排索引
index := map[string][]int{}
for i, word := range words {
for _, w := range strings.Split(word, " ") { // 分词
index[w] = append(index[w], i) // 对词建立索引表
}
}
// search content contains "hello"
for _, idx := range index["hello"] {
fmt.Println(idx, words[idx])
}
}
1 hello jack
2 hello marry
1 hello jack
2 hello marry