feat: Implement delete functionality for generated questions in knowledge base, including API and UI updates
This commit is contained in:
@@ -291,6 +291,11 @@ func (e *elasticsearchRepository) DeleteByChunkIDList(ctx context.Context, chunk
|
||||
return e.deleteByFieldList(ctx, "chunk_id.keyword", chunkIDList)
|
||||
}
|
||||
|
||||
// DeleteBySourceIDList Delete indices by source ID list
|
||||
func (e *elasticsearchRepository) DeleteBySourceIDList(ctx context.Context, sourceIDList []string, dimension int) error {
|
||||
return e.deleteByFieldList(ctx, "source_id.keyword", sourceIDList)
|
||||
}
|
||||
|
||||
// DeleteByKnowledgeIDList Delete indices by knowledge ID list
|
||||
func (e *elasticsearchRepository) DeleteByKnowledgeIDList(ctx context.Context,
|
||||
knowledgeIDList []string, dimension int,
|
||||
|
||||
@@ -184,6 +184,29 @@ func (e *elasticsearchRepository) DeleteByChunkIDList(ctx context.Context, chunk
|
||||
return nil
|
||||
}
|
||||
|
||||
// DeleteBySourceIDList removes documents from the index based on source IDs
|
||||
// Returns an error if the delete operation fails
|
||||
func (e *elasticsearchRepository) DeleteBySourceIDList(ctx context.Context, sourceIDList []string, dimension int) error {
|
||||
log := logger.GetLogger(ctx)
|
||||
if len(sourceIDList) == 0 {
|
||||
log.Warn("[Elasticsearch] Empty source ID list provided for deletion, skipping")
|
||||
return nil
|
||||
}
|
||||
|
||||
log.Infof("[Elasticsearch] Deleting indices by source IDs, count: %d", len(sourceIDList))
|
||||
// Use DeleteByQuery to delete all documents matching the source IDs
|
||||
_, err := e.client.DeleteByQuery(e.index).Query(&types.Query{
|
||||
Terms: &types.TermsQuery{TermsQuery: map[string]types.TermsQueryField{"source_id.keyword": sourceIDList}},
|
||||
}).Do(ctx)
|
||||
if err != nil {
|
||||
log.Errorf("[Elasticsearch] Failed to delete by source IDs: %v", err)
|
||||
return fmt.Errorf("failed to delete by query: %w", err)
|
||||
}
|
||||
|
||||
log.Infof("[Elasticsearch] Successfully deleted documents by source IDs")
|
||||
return nil
|
||||
}
|
||||
|
||||
// DeleteByKnowledgeIDList removes documents from the index based on knowledge IDs
|
||||
// Returns an error if the delete operation fails
|
||||
func (e *elasticsearchRepository) DeleteByKnowledgeIDList(ctx context.Context,
|
||||
|
||||
@@ -118,6 +118,21 @@ func (g *pgRepository) DeleteByChunkIDList(ctx context.Context, chunkIDList []st
|
||||
return nil
|
||||
}
|
||||
|
||||
// DeleteBySourceIDList deletes indices by source IDs
|
||||
func (g *pgRepository) DeleteBySourceIDList(ctx context.Context, sourceIDList []string, dimension int) error {
|
||||
if len(sourceIDList) == 0 {
|
||||
return nil
|
||||
}
|
||||
logger.GetLogger(ctx).Infof("[Postgres] Deleting indices by source IDs, count: %d", len(sourceIDList))
|
||||
result := g.db.WithContext(ctx).Where("source_id IN ?", sourceIDList).Delete(&pgVector{})
|
||||
if result.Error != nil {
|
||||
logger.GetLogger(ctx).Errorf("[Postgres] Failed to delete indices by source IDs: %v", result.Error)
|
||||
return result.Error
|
||||
}
|
||||
logger.GetLogger(ctx).Infof("[Postgres] Successfully deleted %d indices by source IDs", result.RowsAffected)
|
||||
return nil
|
||||
}
|
||||
|
||||
// DeleteByKnowledgeIDList deletes indices by knowledge IDs
|
||||
func (g *pgRepository) DeleteByKnowledgeIDList(ctx context.Context, knowledgeIDList []string, dimension int) error {
|
||||
logger.GetLogger(ctx).Infof("[Postgres] Deleting indices by knowledge IDs, count: %d", len(knowledgeIDList))
|
||||
|
||||
@@ -354,8 +354,8 @@ func getEnrichedPassage(ctx context.Context, result *types.SearchResult) string
|
||||
pipelineWarn(ctx, "Rerank", "chunk_metadata_parse", map[string]interface{}{
|
||||
"error": err.Error(),
|
||||
})
|
||||
} else if len(docMeta.GeneratedQuestions) > 0 {
|
||||
enrichments = append(enrichments, fmt.Sprintf("相关问题: %s", strings.Join(docMeta.GeneratedQuestions, "; ")))
|
||||
} else if questionStrings := docMeta.GetQuestionStrings(); len(questionStrings) > 0 {
|
||||
enrichments = append(enrichments, fmt.Sprintf("相关问题: %s", strings.Join(questionStrings, "; ")))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -5,7 +5,9 @@ package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/application/service/retriever"
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
@@ -18,6 +20,7 @@ type chunkService struct {
|
||||
chunkRepository interfaces.ChunkRepository // Repository for chunk data persistence
|
||||
kbRepository interfaces.KnowledgeBaseRepository
|
||||
modelService interfaces.ModelService
|
||||
retrieveEngine interfaces.RetrieveEngineRegistry
|
||||
}
|
||||
|
||||
// NewChunkService creates a new chunk service
|
||||
@@ -31,11 +34,13 @@ func NewChunkService(
|
||||
chunkRepository interfaces.ChunkRepository,
|
||||
kbRepository interfaces.KnowledgeBaseRepository,
|
||||
modelService interfaces.ModelService,
|
||||
retrieveEngine interfaces.RetrieveEngineRegistry,
|
||||
) interfaces.ChunkService {
|
||||
return &chunkService{
|
||||
chunkRepository: chunkRepository,
|
||||
kbRepository: kbRepository,
|
||||
modelService: modelService,
|
||||
retrieveEngine: retrieveEngine,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -326,3 +331,107 @@ func (s *chunkService) ListChunkByParentID(
|
||||
logger.Info(ctx, "Chunk listed successfully")
|
||||
return chunks, nil
|
||||
}
|
||||
|
||||
// DeleteGeneratedQuestion deletes a single generated question from a chunk by question ID
|
||||
// This updates the chunk metadata and removes the corresponding vector index
|
||||
func (s *chunkService) DeleteGeneratedQuestion(ctx context.Context, chunkID string, questionID string) error {
|
||||
logger.Infof(ctx, "Deleting generated question, chunk ID: %s, question ID: %s", chunkID, questionID)
|
||||
|
||||
tenantID := ctx.Value(types.TenantIDContextKey).(uint64)
|
||||
|
||||
// 1. Get the chunk
|
||||
chunk, err := s.chunkRepository.GetChunkByID(ctx, tenantID, chunkID)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, map[string]interface{}{
|
||||
"chunk_id": chunkID,
|
||||
"tenant_id": tenantID,
|
||||
})
|
||||
return fmt.Errorf("failed to get chunk: %w", err)
|
||||
}
|
||||
|
||||
// 2. Parse the metadata
|
||||
meta, err := chunk.DocumentMetadata()
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, map[string]interface{}{
|
||||
"chunk_id": chunkID,
|
||||
})
|
||||
return fmt.Errorf("failed to parse chunk metadata: %w", err)
|
||||
}
|
||||
|
||||
if meta == nil || len(meta.GeneratedQuestions) == 0 {
|
||||
return fmt.Errorf("no generated questions found for chunk %s", chunkID)
|
||||
}
|
||||
|
||||
// 3. Find the question by ID
|
||||
questionIndex := -1
|
||||
for i, q := range meta.GeneratedQuestions {
|
||||
if q.ID == questionID {
|
||||
questionIndex = i
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if questionIndex == -1 {
|
||||
return fmt.Errorf("question with ID %s not found in chunk %s", questionID, chunkID)
|
||||
}
|
||||
|
||||
// 4. Get knowledge base to get embedding model
|
||||
kb, err := s.kbRepository.GetKnowledgeBaseByID(ctx, chunk.KnowledgeBaseID)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, map[string]interface{}{
|
||||
"knowledge_base_id": chunk.KnowledgeBaseID,
|
||||
})
|
||||
return fmt.Errorf("failed to get knowledge base: %w", err)
|
||||
}
|
||||
|
||||
// 5. Delete the vector index for this question
|
||||
// The source_id format is: {chunk_id}-{question_id}
|
||||
sourceID := fmt.Sprintf("%s-%s", chunkID, questionID)
|
||||
|
||||
tenantInfo := ctx.Value(types.TenantInfoContextKey).(*types.Tenant)
|
||||
retrieveEngine, err := retriever.NewCompositeRetrieveEngine(s.retrieveEngine, tenantInfo.RetrieverEngines.Engines)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, map[string]interface{}{
|
||||
"chunk_id": chunkID,
|
||||
})
|
||||
return fmt.Errorf("failed to create retrieve engine: %w", err)
|
||||
}
|
||||
|
||||
embeddingModel, err := s.modelService.GetEmbeddingModel(ctx, kb.EmbeddingModelID)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, map[string]interface{}{
|
||||
"embedding_model_id": kb.EmbeddingModelID,
|
||||
})
|
||||
return fmt.Errorf("failed to get embedding model: %w", err)
|
||||
}
|
||||
|
||||
// Delete the vector index by source ID
|
||||
if err := retrieveEngine.DeleteBySourceIDList(ctx, []string{sourceID}, embeddingModel.GetDimensions()); err != nil {
|
||||
logger.Warnf(ctx, "Failed to delete vector index for question (may not exist): %v", err)
|
||||
// Continue even if vector deletion fails - the question might not have been indexed
|
||||
}
|
||||
|
||||
// 6. Remove the question from metadata
|
||||
newQuestions := make([]types.GeneratedQuestion, 0, len(meta.GeneratedQuestions)-1)
|
||||
for i, q := range meta.GeneratedQuestions {
|
||||
if i != questionIndex {
|
||||
newQuestions = append(newQuestions, q)
|
||||
}
|
||||
}
|
||||
|
||||
// 7. Update chunk metadata
|
||||
meta.GeneratedQuestions = newQuestions
|
||||
if err := chunk.SetDocumentMetadata(meta); err != nil {
|
||||
return fmt.Errorf("failed to set chunk metadata: %w", err)
|
||||
}
|
||||
|
||||
if err := s.chunkRepository.UpdateChunk(ctx, chunk); err != nil {
|
||||
logger.ErrorWithFields(ctx, err, map[string]interface{}{
|
||||
"chunk_id": chunkID,
|
||||
})
|
||||
return fmt.Errorf("failed to update chunk: %w", err)
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "Successfully deleted generated question %s from chunk %s", questionID, chunkID)
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -1815,9 +1815,17 @@ func (s *knowledgeService) ProcessQuestionGeneration(ctx context.Context, t *asy
|
||||
continue
|
||||
}
|
||||
|
||||
// Update chunk metadata
|
||||
// Update chunk metadata with unique IDs for each question
|
||||
generatedQuestions := make([]types.GeneratedQuestion, len(questions))
|
||||
for j, question := range questions {
|
||||
questionID := fmt.Sprintf("q%d", time.Now().UnixNano()+int64(j))
|
||||
generatedQuestions[j] = types.GeneratedQuestion{
|
||||
ID: questionID,
|
||||
Question: question,
|
||||
}
|
||||
}
|
||||
meta := &types.DocumentChunkMetadata{
|
||||
GeneratedQuestions: questions,
|
||||
GeneratedQuestions: generatedQuestions,
|
||||
}
|
||||
if err := chunk.SetDocumentMetadata(meta); err != nil {
|
||||
logger.Warnf(ctx, "Failed to set document metadata for chunk %s: %v", chunk.ID, err)
|
||||
@@ -1831,10 +1839,10 @@ func (s *knowledgeService) ProcessQuestionGeneration(ctx context.Context, t *asy
|
||||
}
|
||||
|
||||
// Create index entries for generated questions
|
||||
for j, question := range questions {
|
||||
sourceID := fmt.Sprintf("%s-q%d", chunk.ID, j)
|
||||
for _, gq := range generatedQuestions {
|
||||
sourceID := fmt.Sprintf("%s-%s", chunk.ID, gq.ID)
|
||||
indexInfoList = append(indexInfoList, &types.IndexInfo{
|
||||
Content: question,
|
||||
Content: gq.Question,
|
||||
SourceID: sourceID,
|
||||
SourceType: types.ChunkSourceType,
|
||||
ChunkID: chunk.ID,
|
||||
|
||||
@@ -246,6 +246,20 @@ func (c *CompositeRetrieveEngine) DeleteByChunkIDList(ctx context.Context,
|
||||
})
|
||||
}
|
||||
|
||||
// DeleteBySourceIDList deletes vector embeddings by source ID list from all registered repositories
|
||||
func (c *CompositeRetrieveEngine) DeleteBySourceIDList(ctx context.Context,
|
||||
sourceIDList []string, dimension int,
|
||||
) error {
|
||||
return c.concurrentExecWithError(ctx, func(ctx context.Context, engineInfo *engineInfo) error {
|
||||
if err := engineInfo.retrieveEngine.DeleteBySourceIDList(ctx, sourceIDList, dimension); err != nil {
|
||||
logger.GetLogger(ctx).Errorf("Repository %s failed to delete source ID list: %v",
|
||||
engineInfo.retrieveEngine.EngineType(), err)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
// CopyIndices copies indices from a source knowledge base to a target knowledge base
|
||||
func (c *CompositeRetrieveEngine) CopyIndices(
|
||||
ctx context.Context,
|
||||
|
||||
@@ -116,6 +116,13 @@ func (v *KeywordsVectorHybridRetrieveEngineService) DeleteByChunkIDList(ctx cont
|
||||
return v.indexRepository.DeleteByChunkIDList(ctx, indexIDList, dimension)
|
||||
}
|
||||
|
||||
// DeleteBySourceIDList deletes vectors by their source IDs
|
||||
func (v *KeywordsVectorHybridRetrieveEngineService) DeleteBySourceIDList(ctx context.Context,
|
||||
sourceIDList []string, dimension int,
|
||||
) error {
|
||||
return v.indexRepository.DeleteBySourceIDList(ctx, sourceIDList, dimension)
|
||||
}
|
||||
|
||||
// DeleteByKnowledgeIDList deletes vectors by their knowledge IDs
|
||||
func (v *KeywordsVectorHybridRetrieveEngineService) DeleteByKnowledgeIDList(ctx context.Context,
|
||||
knowledgeIDList []string, dimension int,
|
||||
|
||||
Reference in New Issue
Block a user