Files
toutoukan/init/bleveInit/init.go
2025-08-12 17:06:48 +08:00

41 lines
959 B
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package bleveInit
import (
"fmt"
"github.com/blevesearch/bleve/v2"
"log"
"os"
"toutoukan/controllers/search"
)
// 初始化索引(程序启动时调用一次)
func InitIndex() error {
// 检查索引目录是否存在Bleve v2 方式)
_, err := os.Stat("data")
exists := !os.IsNotExist(err)
if err != nil && !os.IsNotExist(err) {
// 除了"不存在"之外的其他错误(如权限问题)
return fmt.Errorf("检查索引目录失败: %v", err)
}
if exists {
// 打开已有索引
search.GlobalIndex, err = bleve.Open("data")
if err != nil {
return fmt.Errorf("打开索引失败: %v", err)
}
log.Println("成功打开已有索引")
} else {
// 创建新索引
mapping := bleve.NewIndexMapping()
search.GlobalIndex, err = bleve.New("data", mapping)
if err != nil {
return fmt.Errorf("创建索引失败: %v", err)
}
log.Println("成功创建新索引")
// 初始化文档(略)
}
return nil
}