更新搜索引擎

This commit is contained in:
2025-08-11 23:10:36 +08:00
parent c617bba52b
commit 61d74561ef
10 changed files with 298 additions and 1 deletions

View File

@@ -0,0 +1,98 @@
package search
import (
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"log"
"toutoukan/model/article"
)
// InsertDocument 插入单条文档到索引
func InsertDocument(c *gin.Context) {
// 检查索引是否初始化
if globalIndex == nil {
c.JSON(500, gin.H{"error": "索引未初始化"})
return
}
// 绑定请求体中的文档数据
var doc article.Document
if err := c.ShouldBindJSON(&doc); err != nil {
c.JSON(400, gin.H{"error": "请求格式错误: " + err.Error()})
return
}
// 验证文档必填字段
if doc.Title == "" && doc.Body == "" {
c.JSON(400, gin.H{"error": "文档ID不能为空且标题和内容不能同时为空"})
return
}
docID := uuid.New().String()
// 将文档插入索引
if err := globalIndex.Index(docID, doc); err != nil {
log.Printf("插入文档失败: %v", err)
c.JSON(500, gin.H{"error": "插入文档到索引失败: " + err.Error()})
return
}
// 插入成功响应
c.JSON(200, gin.H{
"message": "文档插入成功",
"doc_id": docID,
})
}
// BatchInsertDocuments 批量插入文档到索引
//func BatchInsertDocuments(c *gin.Context) {
// // 检查索引是否初始化
// if globalIndex == nil {
// c.JSON(500, gin.H{"error": "索引未初始化"})
// return
// }
//
// // 绑定请求体中的文档数组
// var docs []article.Document
// if err := c.ShouldBindJSON(&docs); err != nil {
// c.JSON(400, gin.H{"error": "请求格式错误: " + err.Error()})
// return
// }
//
// // 验证批量文档
// if len(docs) == 0 {
// c.JSON(400, gin.H{"error": "文档列表不能为空"})
// return
// }
//
// // 批量插入文档
// successCount := 0
// failures := make(map[string]string)
//
// for _, doc := range docs {
// if doc.ID == "" || (doc.Title == "" && doc.Body == "") {
// failures[doc.ID] = "ID不能为空或内容为空"
// continue
// }
//
// if err := globalIndex.Index(doc.ID, doc); err != nil {
// failures[doc.ID] = err.Error()
// continue
// }
// successCount++
// }
//
// // 批量插入结果响应
// response := gin.H{
// "total": len(docs),
// "success": successCount,
// "failed": len(failures),
// "message": fmt.Sprintf("批量插入完成,成功%d条失败%d条", successCount, len(failures)),
// }
//
// if len(failures) > 0 {
// response["failures"] = failures
// }
//
// c.JSON(200, response)
//}