结构更新

This commit is contained in:
2025-08-12 17:06:48 +08:00
parent c383af752f
commit eb5a502d67
6 changed files with 21 additions and 20 deletions

View File

@@ -1,9 +1,8 @@
package search
// 程序退出时关闭索引(可选)
func CloseIndex() error {
if globalIndex != nil {
return globalIndex.Close()
if GlobalIndex != nil {
return GlobalIndex.Close()
}
return nil
}

View File

@@ -1,39 +0,0 @@
package search
import (
"fmt"
"github.com/blevesearch/bleve/v2"
"log"
"os"
)
// 初始化索引(程序启动时调用一次)
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 {
// 打开已有索引
globalIndex, err = bleve.Open("data")
if err != nil {
return fmt.Errorf("打开索引失败: %v", err)
}
log.Println("成功打开已有索引")
} else {
// 创建新索引
mapping := bleve.NewIndexMapping()
globalIndex, err = bleve.New("data", mapping)
if err != nil {
return fmt.Errorf("创建索引失败: %v", err)
}
log.Println("成功创建新索引")
// 初始化文档(略)
}
return nil
}

View File

@@ -10,7 +10,7 @@ import (
// InsertDocument 插入单条文档到索引
func InsertDocument(c *gin.Context) {
// 检查索引是否初始化
if globalIndex == nil {
if GlobalIndex == nil {
c.JSON(500, gin.H{"error": "索引未初始化"})
return
}
@@ -23,15 +23,15 @@ func InsertDocument(c *gin.Context) {
}
// 验证文档必填字段
if doc.Title == "" && doc.Body == "" {
c.JSON(400, gin.H{"error": "文档ID不能为空且标题和内容不能同时为空"})
if doc.Title == "" && doc.Content == "" && doc.AuthorId == "" {
c.JSON(400, gin.H{"error": "用户ID不能为空且标题和内容不能同时为空"})
return
}
docID := uuid.New().String()
// 将文档插入索引
if err := globalIndex.Index(docID, doc); err != nil {
if err := GlobalIndex.Index(docID, doc); err != nil {
log.Printf("插入文档失败: %v", err)
c.JSON(500, gin.H{"error": "插入文档到索引失败: " + err.Error()})
return

View File

@@ -8,10 +8,10 @@ import (
)
// 全局索引变量,避免重复创建
var globalIndex bleve.Index
var GlobalIndex bleve.Index
func DataSearch(c *gin.Context) {
if globalIndex == nil {
if GlobalIndex == nil {
c.JSON(500, gin.H{"error": "索引未初始化请先调用InitIndex()"})
return
}
@@ -22,13 +22,13 @@ func DataSearch(c *gin.Context) {
return
}
query := bleve.NewQueryStringQuery(`title:"` + keyword + `" OR body:"` + keyword + `"`)
query := bleve.NewQueryStringQuery(`title:"` + keyword + `" OR content:"` + keyword + `"`)
searchRequest := bleve.NewSearchRequest(query)
// 只返回必要字段减少资源消耗
searchRequest.Fields = []string{"title", "body"}
searchRequest.Fields = []string{"title", "content"}
searchResult, err := globalIndex.Search(searchRequest)
searchResult, err := GlobalIndex.Search(searchRequest)
if err != nil {
c.JSON(500, gin.H{"error": "搜索失败: " + err.Error()})
return
@@ -53,11 +53,11 @@ func DataSearch(c *gin.Context) {
log.Printf("文档 %s 缺少title字段", hit.ID)
}
if body, ok := hit.Fields["body"].(string); ok {
doc.Body = body
if content, ok := hit.Fields["content"].(string); ok {
doc.Content = content
hasField = true
} else {
log.Printf("文档 %s 缺少body字段", hit.ID)
log.Printf("文档 %s 缺少content字段", hit.ID)
}
// 至少有一个字段存在才包含结果