Files
toutoukan/controllers/search/insert.go
2025-08-12 17:06:48 +08:00

99 lines
2.3 KiB
Go
Raw 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 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.Content == "" && doc.AuthorId == "" {
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)
//}