feat: 新增FAQ推荐标签和批量操作支持,优化标签删除逻辑

This commit is contained in:
wizardchen
2025-12-12 19:57:08 +08:00
committed by lyingbug
parent 5170b11120
commit 3d84bcfd54
23 changed files with 784 additions and 81 deletions
+258 -9
View File
@@ -3,6 +3,7 @@ package repository
import (
"context"
"errors"
"fmt"
"strings"
"github.com/Tencent/WeKnora/internal/common"
@@ -46,7 +47,7 @@ func (r *chunkRepository) ListChunksByID(
ctx context.Context, tenantID uint64, ids []string,
) ([]*types.Chunk, error) {
var chunks []*types.Chunk
if err := r.db.Debug().WithContext(ctx).
if err := r.db.WithContext(ctx).
Where("tenant_id = ? AND id IN ?", tenantID, ids).
Find(&chunks).Error; err != nil {
return nil, err
@@ -103,10 +104,7 @@ func (r *chunkRepository) ListPagedChunksByKnowledgeID(
}
// Then query the paginated data
dataQuery := baseFilter(
r.db.WithContext(ctx).
Select("id, content, knowledge_id, knowledge_base_id, start_at, end_at, chunk_index, is_enabled, chunk_type, parent_chunk_id, image_info, metadata, tag_id, status"),
)
dataQuery := baseFilter(r.db.WithContext(ctx))
if err := dataQuery.
Order("chunk_index ASC").
@@ -133,20 +131,111 @@ func (r *chunkRepository) ListChunkByParentID(
return chunks, nil
}
// UpdateChunk updates a chunk
// UpdateChunk updates a chunk using GORM Save, which updates ALL fields.
// Note: This will update all fields including metadata and content_hash.
// Make sure the chunk object is complete (e.g., fetched from DB) before calling this method.
func (r *chunkRepository) UpdateChunk(ctx context.Context, chunk *types.Chunk) error {
return r.db.WithContext(ctx).Save(chunk).Error
}
// UpdateChunks updates chunks in batch
// UpdateChunks updates chunks in batch using raw SQL for efficiency.
// Uses raw SQL to bypass GORM's default value handling for boolean fields.
//
// IMPORTANT: This method only updates the following fields:
// - content
// - is_enabled
// - tag_id
// - flags
// - status
// - updated_at
//
// Fields NOT updated by this method (will retain their original values):
// - metadata
// - content_hash
// - embedding-related fields
// - other fields not listed above
//
// If you need to update metadata or content_hash, use UpdateChunk (single) instead.
func (r *chunkRepository) UpdateChunks(ctx context.Context, chunks []*types.Chunk) error {
if len(chunks) == 0 {
return nil
}
// Build batch update SQL with CASE expressions
var ids []string
contentCases := make([]string, 0, len(chunks))
isEnabledCases := make([]string, 0, len(chunks))
tagIDCases := make([]string, 0, len(chunks))
flagsCases := make([]string, 0, len(chunks))
statusCases := make([]string, 0, len(chunks))
var contentArgs []interface{}
var isEnabledArgs []interface{}
var tagIDArgs []interface{}
var flagsArgs []interface{}
var statusArgs []interface{}
for _, chunk := range chunks {
chunk.Content = common.CleanInvalidUTF8(chunk.Content)
ids = append(ids, chunk.ID)
content := common.CleanInvalidUTF8(chunk.Content)
contentCases = append(contentCases, "WHEN id = ? THEN ?")
contentArgs = append(contentArgs, chunk.ID, content)
// Convert bool to string for PostgreSQL compatibility
isEnabledStr := "false"
if chunk.IsEnabled {
isEnabledStr = "true"
}
isEnabledCases = append(isEnabledCases, "WHEN id = ? THEN ?")
isEnabledArgs = append(isEnabledArgs, chunk.ID, isEnabledStr)
tagIDCases = append(tagIDCases, "WHEN id = ? THEN ?")
tagIDArgs = append(tagIDArgs, chunk.ID, chunk.TagID)
flagsCases = append(flagsCases, "WHEN id = ? THEN ?")
flagsArgs = append(flagsArgs, chunk.ID, fmt.Sprintf("%d", chunk.Flags))
statusCases = append(statusCases, "WHEN id = ? THEN ?")
statusArgs = append(statusArgs, chunk.ID, fmt.Sprintf("%d", chunk.Status))
}
return r.db.WithContext(ctx).Save(chunks).Error
// Build IN clause placeholders
inPlaceholders := make([]string, len(ids))
for i := range ids {
inPlaceholders[i] = "?"
}
// Combine args in correct order: content, is_enabled, tag_id, flags, status, then IN clause
var args []interface{}
args = append(args, contentArgs...)
args = append(args, isEnabledArgs...)
args = append(args, tagIDArgs...)
args = append(args, flagsArgs...)
args = append(args, statusArgs...)
for _, id := range ids {
args = append(args, id)
}
sql := fmt.Sprintf(`
UPDATE chunks SET
content = CASE %s END,
is_enabled = (CASE %s END)::boolean,
tag_id = CASE %s END,
flags = (CASE %s END)::integer,
status = (CASE %s END)::integer,
updated_at = NOW()
WHERE id IN (%s)
`,
strings.Join(contentCases, " "),
strings.Join(isEnabledCases, " "),
strings.Join(tagIDCases, " "),
strings.Join(flagsCases, " "),
strings.Join(statusCases, " "),
strings.Join(inPlaceholders, ","),
)
return r.db.WithContext(ctx).Exec(sql, args...).Error
}
// DeleteChunk deletes a chunk by its ID
@@ -176,6 +265,13 @@ func (r *chunkRepository) DeleteByKnowledgeList(ctx context.Context, tenantID ui
).Delete(&types.Chunk{}).Error
}
// DeleteChunksByTagID deletes all chunks with the specified tag ID
func (r *chunkRepository) DeleteChunksByTagID(ctx context.Context, tenantID uint64, kbID string, tagID string) error {
return r.db.WithContext(ctx).Where(
"tenant_id = ? AND knowledge_base_id = ? AND tag_id = ?", tenantID, kbID, tagID,
).Delete(&types.Chunk{}).Error
}
// CountChunksByKnowledgeBaseID counts the number of chunks in a knowledge base
func (r *chunkRepository) CountChunksByKnowledgeBaseID(
ctx context.Context,
@@ -292,3 +388,156 @@ func (r *chunkRepository) ListAllFAQChunksWithMetadataByKnowledgeBaseID(
return allChunks, nil
}
// UpdateChunkFlagsBatch updates flags for multiple chunks in batch using SQL CASE expressions.
// This is more efficient than updating chunks one by one.
// setFlags: map of chunk ID to flags to set (OR operation)
// clearFlags: map of chunk ID to flags to clear (AND NOT operation)
func (r *chunkRepository) UpdateChunkFlagsBatch(
ctx context.Context,
tenantID uint64,
kbID string,
setFlags map[string]types.ChunkFlags,
clearFlags map[string]types.ChunkFlags,
) error {
if len(setFlags) == 0 && len(clearFlags) == 0 {
return nil
}
// Collect all IDs
allIDs := make([]string, 0, len(setFlags)+len(clearFlags))
for id := range setFlags {
allIDs = append(allIDs, id)
}
for id := range clearFlags {
if _, exists := setFlags[id]; !exists {
allIDs = append(allIDs, id)
}
}
if len(allIDs) == 0 {
return nil
}
// Build CASE expression for flags update
// flags = (flags | setFlag) & ~clearFlag
var setCases, clearCases []string
var args []interface{}
// Build SET cases: flags | value
for id, flag := range setFlags {
setCases = append(setCases, "WHEN id = ? THEN ?")
args = append(args, id, int(flag))
}
// Build CLEAR cases: flags & ~value
for id, flag := range clearFlags {
clearCases = append(clearCases, "WHEN id = ? THEN ?")
args = append(args, id, int(flag))
}
setExpr := "0"
clearExpr := "0"
if len(setCases) > 0 {
setExpr = fmt.Sprintf("CASE %s ELSE 0 END", strings.Join(setCases, " "))
}
if len(clearCases) > 0 {
clearExpr = fmt.Sprintf("CASE %s ELSE 0 END", strings.Join(clearCases, " "))
}
// Build IN clause placeholders manually for raw SQL
inPlaceholders := make([]string, len(allIDs))
for i := range allIDs {
inPlaceholders[i] = "?"
}
sql := fmt.Sprintf(`
UPDATE chunks
SET flags = (flags | (%s)) & ~(%s),
updated_at = NOW()
WHERE tenant_id = ?
AND knowledge_base_id = ?
AND id IN (%s)
`, setExpr, clearExpr, strings.Join(inPlaceholders, ","))
args = append(args, tenantID, kbID)
for _, id := range allIDs {
args = append(args, id)
}
return r.db.WithContext(ctx).Exec(sql, args...).Error
}
// UpdateChunkFieldsByTagID updates fields for all chunks with the specified tag ID.
// Returns the list of affected chunk IDs for syncing with retriever engines.
func (r *chunkRepository) UpdateChunkFieldsByTagID(
ctx context.Context,
tenantID uint64,
kbID string,
tagID string,
isEnabled *bool,
setFlags types.ChunkFlags,
clearFlags types.ChunkFlags,
) ([]string, error) {
// First, get the IDs of chunks that will be affected (for is_enabled sync)
var affectedIDs []string
if isEnabled != nil {
var chunks []*types.Chunk
query := r.db.WithContext(ctx).
Select("id").
Where("tenant_id = ? AND knowledge_base_id = ? AND chunk_type = ?",
tenantID, kbID, types.ChunkTypeFAQ)
if tagID == "" {
query = query.Where("(tag_id = '' OR tag_id IS NULL)")
} else {
query = query.Where("tag_id = ?", tagID)
}
// Only get chunks that need to change
query = query.Where("is_enabled != ?", *isEnabled)
if err := query.Find(&chunks).Error; err != nil {
return nil, err
}
for _, c := range chunks {
affectedIDs = append(affectedIDs, c.ID)
}
}
// Build update query
updates := map[string]interface{}{
"updated_at": "NOW()",
}
if isEnabled != nil {
updates["is_enabled"] = *isEnabled
}
query := r.db.WithContext(ctx).Model(&types.Chunk{}).
Where("tenant_id = ? AND knowledge_base_id = ? AND chunk_type = ?",
tenantID, kbID, types.ChunkTypeFAQ)
if tagID == "" {
query = query.Where("(tag_id = '' OR tag_id IS NULL)")
} else {
query = query.Where("tag_id = ?", tagID)
}
// Handle flags update
if setFlags != 0 || clearFlags != 0 {
flagsExpr := "flags"
if setFlags != 0 {
flagsExpr = fmt.Sprintf("(%s | %d)", flagsExpr, int(setFlags))
}
if clearFlags != 0 {
flagsExpr = fmt.Sprintf("(%s & ~%d)", flagsExpr, int(clearFlags))
}
updates["flags"] = r.db.Raw(flagsExpr)
}
if err := query.Updates(updates).Error; err != nil {
return nil, err
}
return affectedIDs, nil
}
+11
View File
@@ -40,6 +40,17 @@ func (r *knowledgeTagRepository) GetByID(ctx context.Context, tenantID uint64, i
return &tag, nil
}
// GetByName gets a knowledge tag by name
func (r *knowledgeTagRepository) GetByName(ctx context.Context, tenantID uint64, kbID string, name string) (*types.KnowledgeTag, error) {
var tag types.KnowledgeTag
if err := r.db.WithContext(ctx).
Where("tenant_id = ? AND knowledge_base_id = ? AND name = ?", tenantID, kbID, name).
First(&tag).Error; err != nil {
return nil, err
}
return &tag, nil
}
// ListByKB lists knowledge tags by knowledge base ID with pagination and optional keyword filtering.
func (r *knowledgeTagRepository) ListByKB(
ctx context.Context,
+173 -33
View File
@@ -62,6 +62,7 @@ type knowledgeService struct {
chunkService interfaces.ChunkService
chunkRepo interfaces.ChunkRepository
tagRepo interfaces.KnowledgeTagRepository
tagService interfaces.KnowledgeTagService
fileSvc interfaces.FileService
modelService interfaces.ModelService
task *asynq.Client
@@ -84,6 +85,7 @@ func NewKnowledgeService(
chunkService interfaces.ChunkService,
chunkRepo interfaces.ChunkRepository,
tagRepo interfaces.KnowledgeTagRepository,
tagService interfaces.KnowledgeTagService,
fileSvc interfaces.FileService,
modelService interfaces.ModelService,
task *asynq.Client,
@@ -99,6 +101,7 @@ func NewKnowledgeService(
chunkService: chunkService,
chunkRepo: chunkRepo,
tagRepo: tagRepo,
tagService: tagService,
fileSvc: fileSvc,
modelService: modelService,
task: task,
@@ -2993,6 +2996,17 @@ func (s *knowledgeService) executeFAQImport(ctx context.Context, taskID string,
})
return fmt.Errorf("failed to sanitize entry at index %d: %w", i+idx, err)
}
// 解析 TagID
tagID, err := s.resolveTagID(ctx, kbID, &entry)
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"entry": entry,
"task_id": taskID,
})
return fmt.Errorf("failed to resolve tag for entry at index %d: %w", i+idx, err)
}
isEnabled := true
if entry.IsEnabled != nil {
isEnabled = *entry.IsEnabled
@@ -3007,7 +3021,7 @@ func (s *knowledgeService) executeFAQImport(ctx context.Context, taskID string,
// ChunkIndex: 0,
IsEnabled: isEnabled,
ChunkType: types.ChunkTypeFAQ,
TagID: entry.TagID,
TagID: tagID, // 使用解析后的 TagID
Status: int(types.ChunkStatusStored), // store but not indexed
}
if err := chunk.SetFAQMetadata(meta); err != nil {
@@ -3122,6 +3136,12 @@ func (s *knowledgeService) CreateFAQEntry(ctx context.Context,
return nil, err
}
// 解析 TagID
tagID, err := s.resolveTagID(ctx, kbID, payload)
if err != nil {
return nil, err
}
// 检查标准问和相似问是否与其他条目重复
if err := s.checkFAQQuestionDuplicate(ctx, tenantID, kb.ID, "", meta); err != nil {
return nil, err
@@ -3150,6 +3170,11 @@ func (s *knowledgeService) CreateFAQEntry(ctx context.Context,
if payload.IsEnabled != nil {
isEnabled = *payload.IsEnabled
}
// 默认可推荐
flags := types.ChunkFlagRecommended
if payload.IsRecommended != nil && !*payload.IsRecommended {
flags = 0
}
chunk := &types.Chunk{
ID: uuid.New().String(),
@@ -3158,8 +3183,9 @@ func (s *knowledgeService) CreateFAQEntry(ctx context.Context,
KnowledgeBaseID: kb.ID,
Content: buildFAQChunkContent(meta, indexMode),
IsEnabled: isEnabled,
Flags: flags,
ChunkType: types.ChunkTypeFAQ,
TagID: payload.TagID,
TagID: tagID, // 使用解析后的 TagID
Status: int(types.ChunkStatusStored),
}
@@ -3246,6 +3272,14 @@ func (s *knowledgeService) UpdateFAQEntry(ctx context.Context,
chunk.IsEnabled = *payload.IsEnabled
isEnabledUpdated = (oldEnabled != chunk.IsEnabled)
}
// 处理推荐状态
if payload.IsRecommended != nil {
if *payload.IsRecommended {
chunk.Flags = chunk.Flags.SetFlag(types.ChunkFlagRecommended)
} else {
chunk.Flags = chunk.Flags.ClearFlag(types.ChunkFlagRecommended)
}
}
chunk.UpdatedAt = time.Now()
if err := s.chunkService.UpdateChunk(ctx, chunk); err != nil {
return err
@@ -3317,11 +3351,15 @@ func (s *knowledgeService) UpdateFAQEntryStatus(ctx context.Context,
return nil
}
// UpdateFAQEntryStatusBatch updates enable status for FAQ entries in batch.
func (s *knowledgeService) UpdateFAQEntryStatusBatch(ctx context.Context,
kbID string, updates map[string]bool,
// UpdateFAQEntryFieldsBatch updates multiple fields for FAQ entries in batch.
// This is the unified API for batch updating FAQ entry fields.
// Supports two modes:
// 1. By entry ID: use ByID field
// 2. By Tag: use ByTag field to apply the same update to all entries under a tag
func (s *knowledgeService) UpdateFAQEntryFieldsBatch(ctx context.Context,
kbID string, req *types.FAQEntryFieldsBatchUpdate,
) error {
if len(updates) == 0 {
if req == nil || (len(req.ByID) == 0 && len(req.ByTag) == 0) {
return nil
}
kb, err := s.validateFAQKnowledgeBase(ctx, kbID)
@@ -3330,39 +3368,120 @@ func (s *knowledgeService) UpdateFAQEntryStatusBatch(ctx context.Context,
}
tenantID := ctx.Value(types.TenantIDContextKey).(uint64)
// Get all chunks in batch
entryIDs := make([]string, 0, len(updates))
for entryID := range updates {
entryIDs = append(entryIDs, entryID)
}
chunks, err := s.chunkRepo.ListChunksByID(ctx, tenantID, entryIDs)
if err != nil {
return err
enabledUpdates := make(map[string]bool)
// Handle ByTag updates first
if len(req.ByTag) > 0 {
for tagID, update := range req.ByTag {
var setFlags, clearFlags types.ChunkFlags
// Handle IsRecommended
if update.IsRecommended != nil {
if *update.IsRecommended {
setFlags = types.ChunkFlagRecommended
} else {
clearFlags = types.ChunkFlagRecommended
}
}
// Update all chunks with this tag
affectedIDs, err := s.chunkRepo.UpdateChunkFieldsByTagID(
ctx, tenantID, kb.ID, tagID,
update.IsEnabled, setFlags, clearFlags,
)
if err != nil {
return err
}
// Collect affected IDs for retriever sync
if update.IsEnabled != nil && len(affectedIDs) > 0 {
for _, id := range affectedIDs {
enabledUpdates[id] = *update.IsEnabled
}
}
}
}
// Group chunks by enabled status for batch update
chunkStatusMap := make(map[string]bool)
for _, chunk := range chunks {
if chunk.KnowledgeBaseID != kb.ID || chunk.ChunkType != types.ChunkTypeFAQ {
continue
// Handle ByID updates
if len(req.ByID) > 0 {
entryIDs := make([]string, 0, len(req.ByID))
for entryID := range req.ByID {
entryIDs = append(entryIDs, entryID)
}
isEnabled, exists := updates[chunk.ID]
if !exists {
continue
}
if chunk.IsEnabled == isEnabled {
continue
}
chunk.IsEnabled = isEnabled
chunk.UpdatedAt = time.Now()
if err := s.chunkService.UpdateChunk(ctx, chunk); err != nil {
chunks, err := s.chunkRepo.ListChunksByID(ctx, tenantID, entryIDs)
if err != nil {
return err
}
chunkStatusMap[chunk.ID] = isEnabled
setFlags := make(map[string]types.ChunkFlags)
clearFlags := make(map[string]types.ChunkFlags)
chunksToUpdate := make([]*types.Chunk, 0)
for _, chunk := range chunks {
if chunk.KnowledgeBaseID != kb.ID || chunk.ChunkType != types.ChunkTypeFAQ {
continue
}
update, exists := req.ByID[chunk.ID]
if !exists {
continue
}
needUpdate := false
// Handle IsEnabled
if update.IsEnabled != nil && chunk.IsEnabled != *update.IsEnabled {
chunk.IsEnabled = *update.IsEnabled
enabledUpdates[chunk.ID] = *update.IsEnabled
needUpdate = true
}
// Handle IsRecommended (via Flags)
if update.IsRecommended != nil {
currentRecommended := chunk.Flags.HasFlag(types.ChunkFlagRecommended)
if currentRecommended != *update.IsRecommended {
if *update.IsRecommended {
setFlags[chunk.ID] = types.ChunkFlagRecommended
} else {
clearFlags[chunk.ID] = types.ChunkFlagRecommended
}
}
}
// Handle TagID
if update.TagID != nil {
newTagID := ""
if *update.TagID != "" {
newTagID = *update.TagID
}
if chunk.TagID != newTagID {
chunk.TagID = newTagID
needUpdate = true
}
}
if needUpdate {
chunk.UpdatedAt = time.Now()
chunksToUpdate = append(chunksToUpdate, chunk)
}
}
// Batch update chunks (for IsEnabled and TagID)
if len(chunksToUpdate) > 0 {
if err := s.chunkRepo.UpdateChunks(ctx, chunksToUpdate); err != nil {
return err
}
}
// Batch update flags (for IsRecommended)
if len(setFlags) > 0 || len(clearFlags) > 0 {
if err := s.chunkRepo.UpdateChunkFlagsBatch(ctx, tenantID, kb.ID, setFlags, clearFlags); err != nil {
return err
}
}
}
// Sync update to retriever engines
if len(chunkStatusMap) > 0 {
// Sync enabled status to retriever engines
if len(enabledUpdates) > 0 {
tenantInfo := ctx.Value(types.TenantInfoContextKey).(*types.Tenant)
retrieveEngine, err := retriever.NewCompositeRetrieveEngine(
s.retrieveEngine,
@@ -3371,7 +3490,7 @@ func (s *knowledgeService) UpdateFAQEntryStatusBatch(ctx context.Context,
if err != nil {
return err
}
if err := retrieveEngine.BatchUpdateChunkEnabledStatus(ctx, chunkStatusMap); err != nil {
if err := retrieveEngine.BatchUpdateChunkEnabledStatus(ctx, enabledUpdates); err != nil {
return err
}
}
@@ -3878,6 +3997,7 @@ func (s *knowledgeService) chunkToFAQEntry(chunk *types.Chunk, kb *types.Knowled
KnowledgeBaseID: chunk.KnowledgeBaseID,
TagID: chunk.TagID,
IsEnabled: chunk.IsEnabled,
IsRecommended: chunk.Flags.HasFlag(types.ChunkFlagRecommended),
StandardQuestion: meta.StandardQuestion,
SimilarQuestions: meta.SimilarQuestions,
NegativeQuestions: meta.NegativeQuestions,
@@ -3969,6 +4089,26 @@ func (s *knowledgeService) checkFAQQuestionDuplicate(
return nil
}
// resolveTagID resolves tag ID from payload, prioritizing tag_id over tag_name
func (s *knowledgeService) resolveTagID(ctx context.Context, kbID string, payload *types.FAQEntryPayload) (string, error) {
// 如果提供了 tag_id,优先使用 tag_id
if payload.TagID != "" {
return payload.TagID, nil
}
// 如果提供了 tag_name,查找或创建标签
if payload.TagName != "" && payload.TagName != "未分类" {
tag, err := s.tagService.FindOrCreateTagByName(ctx, kbID, payload.TagName)
if err != nil {
return "", fmt.Errorf("failed to resolve tag by name '%s': %w", payload.TagName, err)
}
return tag.ID, nil
}
// 都没有提供,返回空字符串
return "", nil
}
func sanitizeFAQEntryPayload(payload *types.FAQEntryPayload) (*types.FAQChunkMetadata, error) {
meta := &types.FAQChunkMetadata{
StandardQuestion: strings.TrimSpace(payload.StandardQuestion),
+43 -1
View File
@@ -2,6 +2,7 @@ package service
import (
"context"
"errors"
"strings"
"time"
@@ -10,22 +11,26 @@ import (
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"github.com/google/uuid"
"gorm.io/gorm"
)
// knowledgeTagService implements KnowledgeTagService.
type knowledgeTagService struct {
kbService interfaces.KnowledgeBaseService
repo interfaces.KnowledgeTagRepository
chunkRepo interfaces.ChunkRepository
}
// NewKnowledgeTagService creates a new tag service.
func NewKnowledgeTagService(
kbService interfaces.KnowledgeBaseService,
repo interfaces.KnowledgeTagRepository,
chunkRepo interfaces.ChunkRepository,
) (interfaces.KnowledgeTagService, error) {
return &knowledgeTagService{
kbService: kbService,
repo: repo,
chunkRepo: chunkRepo,
}, nil
}
@@ -147,7 +152,7 @@ func (s *knowledgeTagService) UpdateTag(
return tag, nil
}
// DeleteTag deletes a tag. When force=false, deletion is only allowed if no references exist.
// DeleteTag deletes a tag. When force=true, also deletes all chunks under this tag.
func (s *knowledgeTagService) DeleteTag(ctx context.Context, id string, force bool) error {
if id == "" {
return werrors.NewBadRequestError("标签ID不能为空")
@@ -164,5 +169,42 @@ func (s *knowledgeTagService) DeleteTag(ctx context.Context, id string, force bo
if !force && (kCount > 0 || cCount > 0) {
return werrors.NewBadRequestError("标签仍有知识或FAQ条目引用,无法删除")
}
// When force=true, delete all chunks under this tag first
if force && cCount > 0 {
if err := s.chunkRepo.DeleteChunksByTagID(ctx, tenantID, tag.KnowledgeBaseID, tag.ID); err != nil {
logger.Errorf(ctx, "Failed to delete chunks by tag ID %s: %v", tag.ID, err)
return werrors.NewInternalServerError("删除标签下的数据失败")
}
logger.Infof(ctx, "Deleted %d chunks under tag %s", cCount, tag.ID)
}
return s.repo.Delete(ctx, tenantID, id)
}
// FindOrCreateTagByName finds a tag by name or creates it if not exists.
func (s *knowledgeTagService) FindOrCreateTagByName(ctx context.Context, kbID string, name string) (*types.KnowledgeTag, error) {
name = strings.TrimSpace(name)
if kbID == "" || name == "" {
return nil, werrors.NewBadRequestError("知识库ID和标签名称不能为空")
}
kb, err := s.kbService.GetKnowledgeBaseByID(ctx, kbID)
if err != nil {
return nil, err
}
tenantID := kb.TenantID
// 先尝试查找现有标签
tag, err := s.repo.GetByName(ctx, tenantID, kbID, name)
if err == nil {
return tag, nil
}
// 如果不是 not found 错误,直接返回
if !errors.Is(err, gorm.ErrRecordNotFound) {
return nil, err
}
// 创建新标签
return s.CreateTag(ctx, kbID, name, "", 0)
}