feat: Enhance chunk management and FAQ import functionality

- Updated chunk repository methods to support deletion of unindexed chunks and listing all FAQ chunks by knowledge ID.
- Introduced batch update functionality for chunks in the chunk service.
- Enhanced FAQ import logic to handle append and replace operations, improving efficiency and data integrity.
- Added content hash calculation for FAQ entries to facilitate quick matching and deduplication.
- Refactored related methods to streamline the import process and improve logging for better tracking of import tasks.
This commit is contained in:
wizardchen
2025-11-24 15:47:42 +08:00
parent 385108ce22
commit e56233ef11
9 changed files with 353 additions and 118 deletions
+15
View File
@@ -30,6 +30,17 @@ const (
ChunkTypeWebSearch ChunkType = "web_search"
)
// ChunkStatus 定义了不同状态的 Chunk
type ChunkStatus int
const (
ChunkStatusDefault ChunkStatus = 0
// ChunkStatusStored 表示已存储的 Chunk
ChunkStatusStored ChunkStatus = 1
// ChunkStatusIndexed 表示已索引的 Chunk
ChunkStatusIndexed ChunkStatus = 2
)
// ImageInfo 表示与 Chunk 关联的图片信息
type ImageInfo struct {
// 图片URL(COS)
@@ -69,6 +80,8 @@ type Chunk struct {
ChunkIndex int `json:"chunk_index"`
// Whether the chunk is enabled, can be used to temporarily disable certain chunks
IsEnabled bool `json:"is_enabled" gorm:"default:true"`
// Status of the chunk
Status int `json:"status" gorm:"default:0"`
// Starting character position in the original text
StartAt int `json:"start_at" `
// Ending character position in the original text
@@ -87,6 +100,8 @@ type Chunk struct {
IndirectRelationChunks JSON `json:"indirect_relation_chunks" gorm:"type:json"`
// Metadata 存储 chunk 级别的扩展信息,例如 FAQ 元数据
Metadata JSON `json:"metadata" gorm:"type:json"`
// ContentHash 存储内容的 hash 值,用于快速匹配(主要用于 FAQ)
ContentHash string `json:"content_hash" gorm:"type:varchar(64);index"`
// 图片信息,存储为 JSON
ImageInfo string `json:"image_info" gorm:"type:text"`
// Chunk creation time
+6 -8
View File
@@ -28,14 +28,12 @@ type DocumentProcessPayload struct {
// FAQImportPayload FAQ导入任务payload
type FAQImportPayload struct {
TenantID uint `json:"tenant_id"`
TaskID string `json:"task_id"`
KBID string `json:"kb_id"`
KnowledgeID string `json:"knowledge_id"`
Entries []FAQEntryPayload `json:"entries"`
Mode string `json:"mode"`
StartChunkIndex int `json:"start_chunk_index"`
EndChunkIndex int `json:"end_chunk_index"`
TenantID uint `json:"tenant_id"`
TaskID string `json:"task_id"`
KBID string `json:"kb_id"`
KnowledgeID string `json:"knowledge_id"`
Entries []FAQEntryPayload `json:"entries"`
Mode string `json:"mode"`
}
type PromptTemplateStructured struct {
+46 -1
View File
@@ -1,7 +1,10 @@
package types
import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
"sort"
"strings"
"time"
)
@@ -50,6 +53,7 @@ func (c *Chunk) SetFAQMetadata(meta *FAQChunkMetadata) error {
}
if meta == nil {
c.Metadata = nil
c.ContentHash = ""
return nil
}
meta.Normalize()
@@ -58,9 +62,51 @@ func (c *Chunk) SetFAQMetadata(meta *FAQChunkMetadata) error {
return err
}
c.Metadata = JSON(bytes)
// 计算并设置 ContentHash
c.ContentHash = CalculateFAQContentHash(meta)
return nil
}
// CalculateFAQContentHash 计算 FAQ 内容的 hash 值
// hash 基于:标准问 + 相似问(排序后)+ 反例(排序后)+ 答案(排序后)
// 用于快速匹配和去重
func CalculateFAQContentHash(meta *FAQChunkMetadata) string {
if meta == nil {
return ""
}
// 创建副本并标准化
normalized := *meta
normalized.Normalize()
// 对数组进行排序(确保相同内容产生相同 hash)
similarQuestions := make([]string, len(normalized.SimilarQuestions))
copy(similarQuestions, normalized.SimilarQuestions)
sort.Strings(similarQuestions)
negativeQuestions := make([]string, len(normalized.NegativeQuestions))
copy(negativeQuestions, normalized.NegativeQuestions)
sort.Strings(negativeQuestions)
answers := make([]string, len(normalized.Answers))
copy(answers, normalized.Answers)
sort.Strings(answers)
// 构建用于 hash 的字符串:标准问 + 相似问 + 反例 + 答案
var builder strings.Builder
builder.WriteString(normalized.StandardQuestion)
builder.WriteString("|")
builder.WriteString(strings.Join(similarQuestions, ","))
builder.WriteString("|")
builder.WriteString(strings.Join(negativeQuestions, ","))
builder.WriteString("|")
builder.WriteString(strings.Join(answers, ","))
// 计算 SHA256 hash
hash := sha256.Sum256([]byte(builder.String()))
return hex.EncodeToString(hash[:])
}
// FAQEntry 表示返回给前端的 FAQ 条目
type FAQEntry struct {
ID string `json:"id"`
@@ -125,7 +171,6 @@ type FAQImportMetadata struct {
ImportProgress int `json:"import_progress"` // 0-100
ImportTotal int `json:"import_total"`
ImportProcessed int `json:"import_processed"`
NextChunkIndex int `json:"next_chunk_index,omitempty"` // 下一个要分配的ChunkIndex(自增计数器)
}
// ToJSON converts the metadata to JSON type.
+6 -1
View File
@@ -41,7 +41,10 @@ type ChunkRepository interface {
DeleteByKnowledgeList(ctx context.Context, tenantID uint, knowledgeIDs []string) error
// CountChunksByKnowledgeBaseID counts the number of chunks in a knowledge base.
CountChunksByKnowledgeBaseID(ctx context.Context, tenantID uint, kbID string) (int64, error)
DeleteChunksByChunkIndexRange(ctx context.Context, tenantID uint, knowledgeID string, startChunkIndex int, endChunkIndex int) ([]*types.Chunk, error)
// DeleteUnindexedChunks deletes unindexed chunks by knowledge id and chunk index range
DeleteUnindexedChunks(ctx context.Context, tenantID uint, knowledgeID string) ([]*types.Chunk, error)
// ListAllFAQChunksByKnowledgeID lists all FAQ chunks for a knowledge ID (only ID and ContentHash fields for efficiency)
ListAllFAQChunksByKnowledgeID(ctx context.Context, tenantID uint, knowledgeID string) ([]*types.Chunk, error)
}
// ChunkService defines the interface for chunk service operations
@@ -61,6 +64,8 @@ type ChunkService interface {
) (*types.PageResult, error)
// UpdateChunk updates a chunk
UpdateChunk(ctx context.Context, chunk *types.Chunk) error
// UpdateChunks updates chunks in batch
UpdateChunks(ctx context.Context, chunks []*types.Chunk) error
// DeleteChunk deletes a chunk
DeleteChunk(ctx context.Context, id string) error
// DeleteChunks deletes chunks by IDs in batch