Skip to content

Commit bebeb2a

Browse files
committed
feat: Replace模式清理未使用标签
1 parent 20e7b36 commit bebeb2a

File tree

3 files changed

+22
-0
lines changed

3 files changed

+22
-0
lines changed

internal/application/repository/tag.go

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -156,3 +156,15 @@ func (r *knowledgeTagRepository) CountUntaggedReferences(
156156
}
157157
return
158158
}
159+
160+
// DeleteUnusedTags deletes tags that are not referenced by any knowledge or chunk.
161+
// Returns the number of deleted tags.
162+
func (r *knowledgeTagRepository) DeleteUnusedTags(ctx context.Context, tenantID uint64, kbID string) (int64, error) {
163+
// Delete tags that have no references in both knowledges and chunks tables
164+
result := r.db.WithContext(ctx).
165+
Where("tenant_id = ? AND knowledge_base_id = ?", tenantID, kbID).
166+
Where("id NOT IN (SELECT DISTINCT tag_id FROM knowledges WHERE tenant_id = ? AND knowledge_base_id = ? AND tag_id IS NOT NULL AND tag_id != '')", tenantID, kbID).
167+
Where("id NOT IN (SELECT DISTINCT tag_id FROM chunks WHERE tenant_id = ? AND knowledge_base_id = ? AND tag_id IS NOT NULL AND tag_id != '')", tenantID, kbID).
168+
Delete(&types.KnowledgeTag{})
169+
return result.RowsAffected, result.Error
170+
}

internal/application/service/knowledge.go

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3067,6 +3067,14 @@ func (s *knowledgeService) executeFAQImport(ctx context.Context, taskID string,
30673067
return fmt.Errorf("failed to delete chunk vectors: %w", err)
30683068
}
30693069
logger.Infof(ctx, "FAQ import task %s: deleted %d chunks (including updates)", taskID, len(chunksToDelete))
3070+
3071+
// 清理不再被引用的Tag
3072+
deletedTags, err := s.tagRepo.DeleteUnusedTags(ctx, tenantID, kb.ID)
3073+
if err != nil {
3074+
logger.Warnf(ctx, "FAQ import task %s: failed to cleanup unused tags: %v", taskID, err)
3075+
} else if deletedTags > 0 {
3076+
logger.Infof(ctx, "FAQ import task %s: cleaned up %d unused tags", taskID, deletedTags)
3077+
}
30703078
}
30713079
} else {
30723080
// Append模式:查询已存在的条目,跳过未变化的

internal/types/interfaces/tag.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,4 +54,6 @@ type KnowledgeTagRepository interface {
5454
tenantID uint64,
5555
kbID string,
5656
) (knowledgeCount int64, chunkCount int64, err error)
57+
// DeleteUnusedTags deletes tags that are not referenced by any knowledge or chunk.
58+
DeleteUnusedTags(ctx context.Context, tenantID uint64, kbID string) (int64, error)
5759
}

0 commit comments

Comments
 (0)