feat: Implement knowledge tag management and batch updates for FAQ entries

- Added API functions for listing, creating, updating, and deleting knowledge base tags.
- Introduced batch update functionality for enabling/disabling FAQ entries and updating their tags.
- Enhanced the KnowledgeBase.vue and FAQEntryManager.vue components to support tag management and batch operations.
- Updated localization files to include new strings related to tag management and batch operations.
This commit is contained in:
wizardchen
2025-11-18 11:48:37 +08:00
parent 822041d995
commit fdf5d9d781
29 changed files with 3359 additions and 382 deletions
+12 -1
View File
@@ -93,7 +93,7 @@ func (r *chunkRepository) ListPagedChunksByKnowledgeID(
// Then query the paginated data
dataQuery := 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")
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")
dataQuery = dataQuery.Where("tenant_id = ? AND knowledge_id = ? AND chunk_type IN (?)", tenantID, knowledgeID, chunkType)
if tagID != "" {
dataQuery = dataQuery.Where("tag_id = ?", tagID)
@@ -125,6 +125,17 @@ func (r *chunkRepository) UpdateChunk(ctx context.Context, chunk *types.Chunk) e
return r.db.WithContext(ctx).Save(chunk).Error
}
// UpdateChunks updates chunks in batch
func (r *chunkRepository) UpdateChunks(ctx context.Context, chunks []*types.Chunk) error {
if len(chunks) == 0 {
return nil
}
for _, chunk := range chunks {
chunk.Content = common.CleanInvalidUTF8(chunk.Content)
}
return r.db.WithContext(ctx).Save(chunks).Error
}
// DeleteChunk deletes a chunk by its ID
func (r *chunkRepository) DeleteChunk(ctx context.Context, tenantID uint, id string) error {
return r.db.WithContext(ctx).Where("tenant_id = ? AND id = ?", tenantID, id).Delete(&types.Chunk{}).Error
@@ -97,6 +97,14 @@ func (r *knowledgeRepository) UpdateKnowledge(ctx context.Context, knowledge *ty
return err
}
// UpdateKnowledgeBatch updates knowledge items in batch
func (r *knowledgeRepository) UpdateKnowledgeBatch(ctx context.Context, knowledgeList []*types.Knowledge) error {
if len(knowledgeList) == 0 {
return nil
}
return r.db.WithContext(ctx).Save(knowledgeList).Error
}
// DeleteKnowledge deletes knowledge
func (r *knowledgeRepository) DeleteKnowledge(ctx context.Context, tenantID uint, id string) error {
return r.db.WithContext(ctx).Where("tenant_id = ? AND id = ?", tenantID, id).Delete(&types.Knowledge{}).Error
@@ -16,6 +16,7 @@ type VectorEmbedding struct {
KnowledgeID string `json:"knowledge_id" gorm:"column:knowledge_id"` // ID of the knowledge item
KnowledgeBaseID string `json:"knowledge_base_id" gorm:"column:knowledge_base_id"` // ID of the knowledge base
Embedding []float32 `json:"embedding" gorm:"column:embedding;not null"` // Vector embedding of the content
IsEnabled bool `json:"is_enabled"` // Whether the chunk is enabled
}
// VectorEmbeddingWithScore extends VectorEmbedding with similarity score
@@ -33,6 +34,7 @@ func ToDBVectorEmbedding(embedding *types.IndexInfo, additionalParams map[string
ChunkID: embedding.ChunkID,
KnowledgeID: embedding.KnowledgeID,
KnowledgeBaseID: embedding.KnowledgeBaseID,
IsEnabled: true, // Default to enabled
}
// Add embedding data if available in additionalParams
if additionalParams != nil && slices.Contains(slices.Collect(maps.Keys(additionalParams)), "embedding") {
@@ -40,6 +42,14 @@ func ToDBVectorEmbedding(embedding *types.IndexInfo, additionalParams map[string
vector.Embedding = embeddingMap[embedding.SourceID]
}
}
// Get is_enabled from additionalParams if available
if additionalParams != nil {
if chunkEnabledMap, ok := additionalParams["chunk_enabled"].(map[string]bool); ok {
if enabled, exists := chunkEnabledMap[embedding.ChunkID]; exists {
vector.IsEnabled = enabled
}
}
}
return vector
}
@@ -330,7 +330,7 @@ func (e *elasticsearchRepository) deleteByFieldList(ctx context.Context, field s
if resp.IsError() {
errMsg := fmt.Sprintf("failed to delete by query: %s", resp.String())
log.Errorf("[ElasticsearchV7] %s", errMsg)
return fmt.Errorf(errMsg)
return fmt.Errorf("failed to delete by query: %s", resp.String())
}
// Try to extract deletion count from response
@@ -361,6 +361,9 @@ func (e *elasticsearchRepository) getBaseConds(params typesLocal.RetrieveParams)
// Build MUST_NOT conditions (negative filters)
mustNot := make([]string, 0)
// Exclude disabled chunks (is_enabled = false)
// Note: Historical data without is_enabled field will be included (not matching must_not)
mustNot = append(mustNot, `{"term": {"is_enabled": false}}`)
if len(params.ExcludeKnowledgeIDs) > 0 {
ids, _ := json.Marshal(params.ExcludeKnowledgeIDs)
mustNot = append(mustNot, fmt.Sprintf(`{"terms": {"knowledge_id.keyword": %s}}`, ids))
@@ -371,17 +374,17 @@ func (e *elasticsearchRepository) getBaseConds(params typesLocal.RetrieveParams)
}
// Combine conditions based on presence
switch {
case len(must) == 0 && len(mustNot) == 0:
if len(must) == 0 && len(mustNot) == 0 {
return "{}" // Empty query if no conditions
case len(must) == 0:
return fmt.Sprintf(`{"bool": {"must_not": [%s]}}`, strings.Join(mustNot, ","))
case len(mustNot) == 0:
return fmt.Sprintf(`{"bool": {"must": [%s]}}`, strings.Join(must, ","))
default:
return fmt.Sprintf(`{"bool": {"must": [%s], "must_not": [%s]}}`,
strings.Join(must, ","), strings.Join(mustNot, ","))
}
if len(must) == 0 {
return fmt.Sprintf(`{"bool": {"must_not": [%s]}}`, strings.Join(mustNot, ","))
}
if len(mustNot) == 0 {
return fmt.Sprintf(`{"bool": {"must": [%s]}}`, strings.Join(must, ","))
}
return fmt.Sprintf(`{"bool": {"must": [%s], "must_not": [%s]}}`,
strings.Join(must, ","), strings.Join(mustNot, ","))
}
func (e *elasticsearchRepository) Retrieve(ctx context.Context,
@@ -1028,3 +1031,99 @@ func (e *elasticsearchRepository) saveCopiedIndices(ctx context.Context, indexIn
log.Infof("[ElasticsearchV7] Successfully saved %d indices", len(indexInfoList))
return nil
}
// BatchUpdateChunkEnabledStatus updates the enabled status of chunks in batch
func (e *elasticsearchRepository) BatchUpdateChunkEnabledStatus(ctx context.Context, chunkStatusMap map[string]bool) error {
log := logger.GetLogger(ctx)
if len(chunkStatusMap) == 0 {
log.Warnf("[ElasticsearchV7] Chunk status map is empty, skipping update")
return nil
}
log.Infof("[ElasticsearchV7] Batch updating chunk enabled status, count: %d", len(chunkStatusMap))
// Group chunks by enabled status for batch updates
enabledChunkIDs := make([]string, 0)
disabledChunkIDs := make([]string, 0)
for chunkID, enabled := range chunkStatusMap {
if enabled {
enabledChunkIDs = append(enabledChunkIDs, chunkID)
} else {
disabledChunkIDs = append(disabledChunkIDs, chunkID)
}
}
// Batch update enabled chunks using update_by_query
if len(enabledChunkIDs) > 0 {
query := map[string]interface{}{
"query": map[string]interface{}{
"terms": map[string]interface{}{
"chunk_id.keyword": enabledChunkIDs,
},
},
"script": map[string]interface{}{
"source": "ctx._source.is_enabled = true",
"lang": "painless",
},
}
queryJSON, _ := json.Marshal(query)
res, err := esapi.UpdateByQueryRequest{
Index: []string{e.index},
Body: strings.NewReader(string(queryJSON)),
}.Do(ctx, e.client)
if err != nil {
log.Errorf("[ElasticsearchV7] Failed to update enabled chunks: %v", err)
return err
}
defer res.Body.Close()
if res.IsError() {
var e map[string]interface{}
if err := json.NewDecoder(res.Body).Decode(&e); err != nil {
log.Errorf("[ElasticsearchV7] Error parsing the response body: %v", err)
} else {
log.Errorf("[ElasticsearchV7] Error updating enabled chunks: %v", e["error"])
}
return fmt.Errorf("elasticsearch update_by_query failed with status: %d", res.StatusCode)
}
log.Infof("[ElasticsearchV7] Updated %d chunks to enabled", len(enabledChunkIDs))
}
// Batch update disabled chunks using update_by_query
if len(disabledChunkIDs) > 0 {
query := map[string]interface{}{
"query": map[string]interface{}{
"terms": map[string]interface{}{
"chunk_id.keyword": disabledChunkIDs,
},
},
"script": map[string]interface{}{
"source": "ctx._source.is_enabled = false",
"lang": "painless",
},
}
queryJSON, _ := json.Marshal(query)
res, err := esapi.UpdateByQueryRequest{
Index: []string{e.index},
Body: strings.NewReader(string(queryJSON)),
}.Do(ctx, e.client)
if err != nil {
log.Errorf("[ElasticsearchV7] Failed to update disabled chunks: %v", err)
return err
}
defer res.Body.Close()
if res.IsError() {
var e map[string]interface{}
if err := json.NewDecoder(res.Body).Decode(&e); err != nil {
log.Errorf("[ElasticsearchV7] Error parsing the response body: %v", err)
} else {
log.Errorf("[ElasticsearchV7] Error updating disabled chunks: %v", e["error"])
}
return fmt.Errorf("elasticsearch update_by_query failed with status: %d", res.StatusCode)
}
log.Infof("[ElasticsearchV7] Updated %d chunks to disabled", len(disabledChunkIDs))
}
log.Infof("[ElasticsearchV7] Successfully batch updated chunk enabled status")
return nil
}
@@ -14,6 +14,7 @@ import (
"github.com/elastic/go-elasticsearch/v8"
"github.com/elastic/go-elasticsearch/v8/typedapi/core/search"
"github.com/elastic/go-elasticsearch/v8/typedapi/types"
"github.com/elastic/go-elasticsearch/v8/typedapi/types/enums/scriptlanguage"
)
// elasticsearchRepository implements the RetrieveEngineRepository interface for Elasticsearch v8
@@ -220,6 +221,11 @@ func (e *elasticsearchRepository) getBaseConds(params typesLocal.RetrieveParams)
}})
}
mustNot := make([]types.Query, 0)
// Exclude disabled chunks (is_enabled = false)
// Note: Historical data without is_enabled field will be included (not matching must_not)
mustNot = append(mustNot, types.Query{Term: map[string]types.TermQuery{
"is_enabled": {Value: false},
}})
if len(params.ExcludeKnowledgeIDs) > 0 {
mustNot = append(mustNot, types.Query{Terms: &types.TermsQuery{
TermsQuery: map[string]types.TermsQueryField{"knowledge_id.keyword": params.ExcludeKnowledgeIDs},
@@ -539,3 +545,81 @@ func (e *elasticsearchRepository) CopyIndices(ctx context.Context,
log.Infof("[Elasticsearch] Index copy completed, total copied: %d", totalCopied)
return nil
}
// BatchUpdateChunkEnabledStatus updates the enabled status of chunks in batch
func (e *elasticsearchRepository) BatchUpdateChunkEnabledStatus(ctx context.Context, chunkStatusMap map[string]bool) error {
log := logger.GetLogger(ctx)
if len(chunkStatusMap) == 0 {
log.Warnf("[Elasticsearch] Chunk status map is empty, skipping update")
return nil
}
log.Infof("[Elasticsearch] Batch updating chunk enabled status, count: %d", len(chunkStatusMap))
// Group chunks by enabled status for batch updates
enabledChunkIDs := make([]string, 0)
disabledChunkIDs := make([]string, 0)
for chunkID, enabled := range chunkStatusMap {
if enabled {
enabledChunkIDs = append(enabledChunkIDs, chunkID)
} else {
disabledChunkIDs = append(disabledChunkIDs, chunkID)
}
}
// Batch update enabled chunks using update_by_query
if len(enabledChunkIDs) > 0 {
query := types.NewQuery()
query.Bool = &types.BoolQuery{
Must: []types.Query{
{Terms: &types.TermsQuery{
TermsQuery: map[string]types.TermsQueryField{
"chunk_id.keyword": enabledChunkIDs,
},
}},
},
}
source := "ctx._source.is_enabled = true"
lang := scriptlanguage.Painless
script := types.Script{
Source: &source,
Lang: &lang,
}
_, err := e.client.UpdateByQuery(e.index).Query(query).Script(&script).Do(ctx)
if err != nil {
log.Errorf("[Elasticsearch] Failed to update enabled chunks: %v", err)
return err
}
log.Infof("[Elasticsearch] Updated %d chunks to enabled", len(enabledChunkIDs))
}
// Batch update disabled chunks using update_by_query
if len(disabledChunkIDs) > 0 {
query := types.NewQuery()
query.Bool = &types.BoolQuery{
Must: []types.Query{
{Terms: &types.TermsQuery{
TermsQuery: map[string]types.TermsQueryField{
"chunk_id.keyword": disabledChunkIDs,
},
}},
},
}
source := "ctx._source.is_enabled = false"
lang := scriptlanguage.Painless
script := types.Script{
Source: &source,
Lang: &lang,
}
_, err := e.client.UpdateByQuery(e.index).Query(query).Script(&script).Do(ctx)
if err != nil {
log.Errorf("[Elasticsearch] Failed to update disabled chunks: %v", err)
return err
}
log.Infof("[Elasticsearch] Updated %d chunks to disabled", len(disabledChunkIDs))
}
log.Infof("[Elasticsearch] Successfully batch updated chunk enabled status")
return nil
}
@@ -159,6 +159,11 @@ func (g *pgRepository) KeywordsRetrieve(ctx context.Context,
SQL: "id @@@ paradedb.match(field => 'content', value => ?, distance => 1)",
Vars: []interface{}{params.Query},
})
// Filter by is_enabled = true or NULL (NULL means enabled for historical data)
conds = append(conds, clause.Expr{
SQL: "(is_enabled IS NULL OR is_enabled = ?)",
Vars: []interface{}{true},
})
conds = append(conds, clause.OrderBy{Columns: []clause.OrderByColumn{
{Column: clause.Column{Name: "score"}, Desc: true},
}})
@@ -227,6 +232,11 @@ func (g *pgRepository) VectorRetrieve(ctx context.Context,
// <#> Inner product operator
dimension := len(params.Embedding)
conds = append(conds, clause.Expr{SQL: "dimension = ?", Vars: []interface{}{dimension}})
// Filter by is_enabled = true or NULL (NULL means enabled for historical data)
conds = append(conds, clause.Expr{
SQL: "(is_enabled IS NULL OR is_enabled = ?)",
Vars: []interface{}{true},
})
conds = append(conds, clause.Expr{
SQL: fmt.Sprintf("embedding::halfvec(%d) <=> ?::halfvec < ?", dimension),
Vars: []interface{}{pgvector.NewHalfVector(params.Embedding), 1 - params.Threshold},
@@ -388,3 +398,52 @@ func (g *pgRepository) CopyIndices(ctx context.Context,
logger.GetLogger(ctx).Infof("[Postgres] Index copying completed, total copied: %d", totalCopied)
return nil
}
// BatchUpdateChunkEnabledStatus updates the enabled status of chunks in batch
func (g *pgRepository) BatchUpdateChunkEnabledStatus(ctx context.Context, chunkStatusMap map[string]bool) error {
if len(chunkStatusMap) == 0 {
logger.GetLogger(ctx).Warnf("[Postgres] Chunk status map is empty, skipping update")
return nil
}
logger.GetLogger(ctx).Infof("[Postgres] Batch updating chunk enabled status, count: %d", len(chunkStatusMap))
// Group chunks by enabled status for batch updates
enabledChunkIDs := make([]string, 0)
disabledChunkIDs := make([]string, 0)
for chunkID, enabled := range chunkStatusMap {
if enabled {
enabledChunkIDs = append(enabledChunkIDs, chunkID)
} else {
disabledChunkIDs = append(disabledChunkIDs, chunkID)
}
}
// Batch update enabled chunks
if len(enabledChunkIDs) > 0 {
result := g.db.WithContext(ctx).Model(&pgVector{}).
Where("chunk_id IN ?", enabledChunkIDs).
Update("is_enabled", true)
if result.Error != nil {
logger.GetLogger(ctx).Errorf("[Postgres] Failed to update enabled chunks: %v", result.Error)
return result.Error
}
logger.GetLogger(ctx).Infof("[Postgres] Updated %d chunks to enabled, rows affected: %d", len(enabledChunkIDs), result.RowsAffected)
}
// Batch update disabled chunks
if len(disabledChunkIDs) > 0 {
result := g.db.WithContext(ctx).Model(&pgVector{}).
Where("chunk_id IN ?", disabledChunkIDs).
Update("is_enabled", false)
if result.Error != nil {
logger.GetLogger(ctx).Errorf("[Postgres] Failed to update disabled chunks: %v", result.Error)
return result.Error
}
logger.GetLogger(ctx).Infof("[Postgres] Updated %d chunks to disabled, rows affected: %d", len(disabledChunkIDs), result.RowsAffected)
}
logger.GetLogger(ctx).Infof("[Postgres] Successfully batch updated chunk enabled status")
return nil
}
@@ -24,6 +24,7 @@ type pgVector struct {
Content string `json:"content" gorm:"column:content;not null"`
Dimension int `json:"dimension" gorm:"column:dimension;not null"`
Embedding pgvector.HalfVector `json:"embedding" gorm:"column:embedding;not null"`
IsEnabled bool `json:"is_enabled" gorm:"column:is_enabled;default:true;index"`
}
// pgVectorWithScore extends pgVector with similarity score field
@@ -39,6 +40,7 @@ type pgVectorWithScore struct {
Content string `json:"content" gorm:"column:content;not null"`
Dimension int `json:"dimension" gorm:"column:dimension;not null"`
Embedding pgvector.HalfVector `json:"embedding" gorm:"column:embedding;not null"`
IsEnabled bool `json:"is_enabled" gorm:"column:is_enabled;default:true;index"`
Score float64 `json:"score" gorm:"column:score"`
}
@@ -61,6 +63,7 @@ func toDBVectorEmbedding(indexInfo *types.IndexInfo, additionalParams map[string
KnowledgeID: indexInfo.KnowledgeID,
KnowledgeBaseID: indexInfo.KnowledgeBaseID,
Content: common.CleanInvalidUTF8(indexInfo.Content),
IsEnabled: true, // Default to enabled
}
// Add embedding data if available in additionalParams
if additionalParams != nil && slices.Contains(slices.Collect(maps.Keys(additionalParams)), "embedding") {
@@ -69,6 +72,14 @@ func toDBVectorEmbedding(indexInfo *types.IndexInfo, additionalParams map[string
pgVector.Dimension = len(pgVector.Embedding.Slice())
}
}
// Get is_enabled from additionalParams if available
if additionalParams != nil {
if chunkEnabledMap, ok := additionalParams["chunk_enabled"].(map[string]bool); ok {
if enabled, exists := chunkEnabledMap[indexInfo.ChunkID]; exists {
pgVector.IsEnabled = enabled
}
}
}
return pgVector
}