86 lines
2.0 KiB
Go
86 lines
2.0 KiB
Go
|
|
package search
|
|||
|
|
|
|||
|
|
import (
|
|||
|
|
"github.com/blevesearch/bleve/v2"
|
|||
|
|
"github.com/gin-gonic/gin"
|
|||
|
|
"log"
|
|||
|
|
"toutoukan/model/article"
|
|||
|
|
)
|
|||
|
|
|
|||
|
|
// 全局索引变量,避免重复创建
|
|||
|
|
var globalIndex bleve.Index
|
|||
|
|
|
|||
|
|
func DataSearch(c *gin.Context) {
|
|||
|
|
if globalIndex == nil {
|
|||
|
|
c.JSON(500, gin.H{"error": "索引未初始化,请先调用InitIndex()"})
|
|||
|
|
return
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
keyword := c.Query("keyword")
|
|||
|
|
if keyword == "" {
|
|||
|
|
c.JSON(400, gin.H{"error": "请提供搜索关键词(?keyword=xxx)"})
|
|||
|
|
return
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
query := bleve.NewQueryStringQuery(`title:"` + keyword + `" OR body:"` + keyword + `"`)
|
|||
|
|
searchRequest := bleve.NewSearchRequest(query)
|
|||
|
|
|
|||
|
|
// 只返回必要字段减少资源消耗
|
|||
|
|
searchRequest.Fields = []string{"title", "body"}
|
|||
|
|
|
|||
|
|
searchResult, err := globalIndex.Search(searchRequest)
|
|||
|
|
if err != nil {
|
|||
|
|
c.JSON(500, gin.H{"error": "搜索失败: " + err.Error()})
|
|||
|
|
return
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
type Result struct {
|
|||
|
|
ID string `json:"id"`
|
|||
|
|
Score float64 `json:"score"`
|
|||
|
|
Doc *article.Document `json:"doc"`
|
|||
|
|
}
|
|||
|
|
var results []Result
|
|||
|
|
|
|||
|
|
for _, hit := range searchResult.Hits {
|
|||
|
|
doc := &article.Document{}
|
|||
|
|
hasField := false
|
|||
|
|
|
|||
|
|
// 宽松的字段处理逻辑
|
|||
|
|
if title, ok := hit.Fields["title"].(string); ok {
|
|||
|
|
doc.Title = title
|
|||
|
|
hasField = true
|
|||
|
|
} else {
|
|||
|
|
log.Printf("文档 %s 缺少title字段", hit.ID)
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
if body, ok := hit.Fields["body"].(string); ok {
|
|||
|
|
doc.Body = body
|
|||
|
|
hasField = true
|
|||
|
|
} else {
|
|||
|
|
log.Printf("文档 %s 缺少body字段", hit.ID)
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// 至少有一个字段存在才包含结果
|
|||
|
|
if hasField {
|
|||
|
|
results = append(results, Result{
|
|||
|
|
ID: hit.ID,
|
|||
|
|
Score: hit.Score,
|
|||
|
|
Doc: doc,
|
|||
|
|
})
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// 添加调试信息
|
|||
|
|
if len(results) == 0 {
|
|||
|
|
log.Printf("关键词'%s'搜索返回%d个文档,但有效结果为0", keyword, searchResult.Total)
|
|||
|
|
} else {
|
|||
|
|
log.Printf("关键词'%s'搜索返回%d个文档", keyword, searchResult.Total)
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
c.JSON(200, gin.H{
|
|||
|
|
"total": len(results), // 返回实际有效结果数
|
|||
|
|
"took": searchResult.Took,
|
|||
|
|
"result": results,
|
|||
|
|
})
|
|||
|
|
}
|