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
+36
View File
@@ -90,6 +90,38 @@ export function getChunkByIdOnly(chunkId: string) {
return get(`/api/v1/chunks/by-id/${chunkId}`);
}
export function listKnowledgeTags(kbId: string) {
return get(`/api/v1/knowledge-bases/${kbId}/tags`);
}
export function createKnowledgeBaseTag(
kbId: string,
data: { name: string; color?: string; sort_order?: number },
) {
return post(`/api/v1/knowledge-bases/${kbId}/tags`, data);
}
export function updateKnowledgeBaseTag(
kbId: string,
tagId: string,
data: { name?: string; color?: string; sort_order?: number },
) {
return put(`/api/v1/knowledge-bases/${kbId}/tags/${tagId}`, data);
}
export function deleteKnowledgeBaseTag(kbId: string, tagId: string, params?: { force?: boolean }) {
const forceQuery = params?.force ? '?force=true' : '';
return del(`/api/v1/knowledge-bases/${kbId}/tags/${tagId}${forceQuery}`);
}
export function updateKnowledgeTagBatch(data: { updates: Record<string, string | null> }) {
return put(`/api/v1/knowledge/tags`, data);
}
export function updateFAQEntryTagBatch(kbId: string, data: { updates: Record<string, string | null> }) {
return put(`/api/v1/knowledge-bases/${kbId}/faq/entries/tags`, data);
}
const buildQuery = (params?: Record<string, any>) => {
if (!params) return '';
const query = new URLSearchParams();
@@ -114,6 +146,10 @@ export function updateFAQEntry(kbId: string, entryId: string, data: any) {
return put(`/api/v1/knowledge-bases/${kbId}/faq/entries/${entryId}`, data);
}
export function updateFAQEntryStatusBatch(kbId: string, data: { updates: Record<string, boolean> }) {
return put(`/api/v1/knowledge-bases/${kbId}/faq/entries/status`, data);
}
export function deleteFAQEntries(kbId: string, ids: string[]) {
return del(`/api/v1/knowledge-bases/${kbId}/faq/entries`, { ids });
}
-12
View File
@@ -3,7 +3,6 @@ import { marked } from "marked";
import { onMounted, ref, nextTick, onUnmounted, onUpdated, watch } from "vue";
import { downKnowledgeDetails } from "@/api/knowledge-base/index";
import { MessagePlugin } from "tdesign-vue-next";
import picturePreview from '@/components/picture-preview.vue';
import { sanitizeHTML, safeMarkdownToHTML, createSafeImage, isValidImageURL } from '@/utils/security';
import { useI18n } from 'vue-i18n';
@@ -19,8 +18,6 @@ let doc = null;
let down = ref()
let mdContentWrap = ref()
let url = ref('')
let reviewUrl = ref('')
let reviewImg = ref(false)
onMounted(() => {
nextTick(() => {
doc = document.getElementsByClassName('t-drawer__body')[0]
@@ -61,10 +58,6 @@ watch(() => props.details.md, (newVal) => {
const images = mdContentWrap.value.querySelectorAll('img.markdown-image');
if (images) {
images.forEach(async item => {
item.addEventListener('click', function (event) {
reviewUrl.value = event.target.src;
reviewImg.value = true
})
const isValid = await checkImage(item.src);
if (!isValid) {
item.remove();
@@ -103,10 +96,6 @@ const processMarkdown = (markdownText) => {
return sanitizedHTML;
};
const closePreImg = () => {
reviewImg.value = false
reviewUrl.value = '';
}
const handleClose = () => {
emit("closeDoc", false);
doc.scrollTop = 0;
@@ -179,7 +168,6 @@ const handleDetailsScroll = () => {
<t-button theme="default" @click="handleClose">{{ $t('common.cancel') }}</t-button>
</template>
</t-drawer>
<picturePreview :reviewImg="reviewImg" :reviewUrl="reviewUrl" @closePreImg="closePreImg"></picturePreview>
</div>
</template>
<style scoped lang="less">
+4 -1
View File
@@ -24,7 +24,10 @@ export default function (knowledgeBaseId?: string) {
id: "",
total: 0
});
const getKnowled = (query = { page: 1, page_size: 35 }, kbId?: string) => {
const getKnowled = (
query: { page: number; page_size: number; tag_id?: string } = { page: 1, page_size: 35 },
kbId?: string,
) => {
const targetKbId = kbId || knowledgeBaseId;
if (!targetKbId) return;
+33
View File
@@ -24,6 +24,27 @@ export default {
description: 'Description',
files: 'Files',
settings: 'Settings',
documentCategoryTitle: 'Document Categories',
tagUpdateSuccess: 'Tag updated successfully',
category: 'Category',
faqCategoryTitle: 'FAQ Categories',
untagged: 'Uncategorized',
tagSearchTooltip: 'Search tags',
tagCreateAction: 'Create tag',
tagSearchPlaceholder: 'Type to filter tags',
tagNamePlaceholder: 'Enter tag name',
tagNameRequired: 'Please provide a tag name',
tagCreateSuccess: 'Tag created',
tagEditSuccess: 'Tag updated',
tagDeleteTitle: 'Delete tag',
tagDeleteDesc: 'Delete tag "{name}"? Related FAQs will become untagged.',
tagDeleteSuccess: 'Tag deleted',
tagEditAction: 'Rename',
tagDeleteAction: 'Delete',
tagEmptyResult: 'No matching tags',
tagLabel: 'Category',
tagPlaceholder: 'Please select a category',
noTags: 'No categories',
upload: 'Upload File',
uploadSuccess: 'File uploaded successfully!',
uploadFailed: 'File upload failed!',
@@ -730,6 +751,7 @@ export default {
questionIndexModeLabel: 'Question Indexing Mode',
questionIndexModeDescription: 'Combined: Standard and similar questions are indexed together. Separate: Each question is indexed independently for more precise retrieval but requires more storage.',
entryGuide: 'Each FAQ entry contains a primary question, similar questions, negative examples, and multiple answers. Manage them in the FAQ knowledge base detail view.',
tagDesc: 'Select category for FAQ entries',
modes: {
questionOnly: 'Questions only',
questionAnswer: 'Question + answer',
@@ -740,6 +762,8 @@ export default {
answers: 'Answers',
similarQuestions: 'Similar Questions',
negativeQuestions: 'Negative Examples',
categoryLabel: 'FAQ Category',
categoryButton: 'Switch Category',
editorCreate: 'Create FAQ Entry',
editorEdit: 'Edit FAQ Entry',
addAnswer: 'Add Answer',
@@ -771,6 +795,15 @@ export default {
matchTypeEmbedding: 'Vector Match',
matchTypeKeywords: 'Keyword Match',
similarityThresholdLabel: 'Similarity Threshold',
statusEnabled: 'Enabled',
statusDisabled: 'Disabled',
statusEnableSuccess: 'FAQ entry enabled',
statusDisableSuccess: 'FAQ entry disabled',
statusUpdateFailed: 'Failed to update status',
batchUpdateTag: 'Batch Update Category',
batchUpdateTagTip: 'Set category for {count} selected entries',
batchEnable: 'Batch Enable',
batchDisable: 'Batch Disable',
},
faqImport: {
title: 'Batch Import FAQ',
+33
View File
@@ -24,6 +24,27 @@ export default {
description: 'Описание',
files: 'Файлы',
settings: 'Настройки',
documentCategoryTitle: 'Категории документов',
faqCategoryTitle: 'Категории FAQ',
untagged: 'Без метки',
tagSearchTooltip: 'Поиск тегов',
tagUpdateSuccess: 'Тег успешно обновлен',
category: 'Категория',
tagCreateAction: 'Создать тег',
tagSearchPlaceholder: 'Введите название тега',
tagNamePlaceholder: 'Введите название тега',
tagNameRequired: 'Пожалуйста, укажите название тега',
tagCreateSuccess: 'Тег создан',
tagEditSuccess: 'Тег обновлён',
tagDeleteTitle: 'Удаление тега',
tagDeleteDesc: 'Удалить тег «{name}»? Связанные FAQ будут без метки.',
tagDeleteSuccess: 'Тег удалён',
tagEditAction: 'Переименовать',
tagDeleteAction: 'Удалить',
tagEmptyResult: 'Подходящие теги не найдены',
tagLabel: 'Категория',
tagPlaceholder: 'Пожалуйста, выберите категорию',
noTags: 'Нет категорий',
upload: 'Загрузить файл',
uploadSuccess: 'Файл успешно загружен!',
uploadFailed: 'Ошибка загрузки файла!',
@@ -820,6 +841,7 @@ export default {
questionIndexModeLabel: 'Режим индексации вопросов',
questionIndexModeDescription: 'Объединенная: стандартные и похожие вопросы индексируются вместе. Раздельная: каждый вопрос индексируется независимо для более точного поиска, но требует больше места.',
entryGuide: 'Каждый FAQ включает основной вопрос, похожие вопросы, негативные примеры и несколько ответов. Управляйте ими в деталях FAQ-базы.',
tagDesc: 'Выберите категорию для записей FAQ',
modes: {
questionOnly: 'Только вопросы',
questionAnswer: 'Вопрос + ответ',
@@ -830,6 +852,8 @@ export default {
answers: 'Ответы',
similarQuestions: 'Похожие вопросы',
negativeQuestions: 'Негативные примеры',
categoryLabel: 'Категория FAQ',
categoryButton: 'Сменить категорию',
editorCreate: 'Создать FAQ запись',
editorEdit: 'Редактировать FAQ запись',
addAnswer: 'Добавить ответ',
@@ -861,6 +885,15 @@ export default {
matchTypeEmbedding: 'Векторное совпадение',
matchTypeKeywords: 'Совпадение ключевых слов',
similarityThresholdLabel: 'Порог сходства',
statusEnabled: 'Включено',
statusDisabled: 'Выключено',
statusEnableSuccess: 'Запись FAQ включена',
statusDisableSuccess: 'Запись FAQ отключена',
statusUpdateFailed: 'Не удалось обновить статус',
batchUpdateTag: 'Пакетное обновление категории',
batchUpdateTagTip: 'Установить категорию для {count} выбранных записей',
batchEnable: 'Пакетное включение',
batchDisable: 'Пакетное отключение',
},
faqImport: {
title: 'Пакетный импорт FAQ',
+33
View File
@@ -24,6 +24,27 @@ export default {
description: "描述",
files: "文件",
settings: "设置",
documentCategoryTitle: "文档分类",
faqCategoryTitle: "问题分类",
untagged: "未分类",
tagUpdateSuccess: "标签更新成功",
tagSearchTooltip: "搜索标签",
category: "分类",
tagCreateAction: "新建标签",
tagSearchPlaceholder: "输入标签名称关键字",
tagNamePlaceholder: "请输入标签名称",
tagNameRequired: "请先输入标签名称",
tagCreateSuccess: "标签创建成功",
tagEditSuccess: "标签更新成功",
tagDeleteTitle: "删除标签",
tagDeleteDesc: "确定删除标签“{name}”?已关联的 FAQ 将被标记为未分类",
tagDeleteSuccess: "标签已删除",
tagEditAction: "重命名",
tagDeleteAction: "删除",
tagEmptyResult: "未找到匹配的标签",
tagLabel: "分类",
tagPlaceholder: "请选择分类",
noTags: "暂无分类",
upload: "上传文件",
uploadSuccess: "文件上传成功!",
uploadFailed: "文件上传失败!",
@@ -1049,6 +1070,7 @@ export default {
questionIndexModeLabel: "问题索引方式",
questionIndexModeDescription: "合并索引:标准问和相似问合并索引;分别索引:标准问和每个相似问独立索引,检索更精确但需要更多存储",
entryGuide: "FAQ 条目由标准问、相似问、反例和多个答案组成,可在知识库详情中批量导入、编辑。",
tagDesc: "为 FAQ 条目选择分类",
modes: {
questionOnly: "仅标准问/相似问",
questionAnswer: "标准问 + 答案",
@@ -1063,6 +1085,8 @@ export default {
similarQuestionsDesc: "添加与标准问意思相同但表述不同的问题,帮助系统更好地匹配用户查询。",
negativeQuestions: "反例",
negativeQuestionsDesc: "添加不应匹配此答案的问题,用于排除误匹配的情况。",
categoryLabel: "FAQ 分类",
categoryButton: "切换分类",
editorCreate: "新增 FAQ 条目",
editorEdit: "编辑 FAQ 条目",
addAnswer: "添加答案",
@@ -1094,6 +1118,15 @@ export default {
matchTypeEmbedding: "向量匹配",
matchTypeKeywords: "关键词匹配",
similarityThresholdLabel: "相似度阈值",
statusEnabled: "已启用",
statusDisabled: "已禁用",
statusEnableSuccess: "FAQ 条目已启用",
statusDisableSuccess: "FAQ 条目已禁用",
statusUpdateFailed: "更新状态失败",
batchUpdateTag: "批量分类",
batchUpdateTagTip: "将为 {count} 个选中的条目设置分类",
batchEnable: "批量启用",
batchDisable: "批量禁用",
},
faqImport: {
title: "批量导入 FAQ",
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+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
}
@@ -307,7 +307,7 @@ func (s *agentService) getKnowledgeBaseInfos(ctx context.Context, kbIDs []string
pageResult, err := s.knowledgeService.ListFAQEntries(ctx, kbID, &types.Pagination{
Page: 1,
PageSize: 10,
})
}, "")
if err == nil && pageResult != nil {
docCount = int(pageResult.Total)
if entries, ok := pageResult.Data.([]*types.FAQEntry); ok {
@@ -336,7 +336,7 @@ func (s *agentService) getKnowledgeBaseInfos(ctx context.Context, kbIDs []string
pageResult, err := s.knowledgeService.ListPagedKnowledgeByKnowledgeBaseID(ctx, kbID, &types.Pagination{
Page: 1,
PageSize: 10,
})
}, "")
if err == nil && pageResult != nil {
docCount = int(pageResult.Total)
+338 -1
View File
@@ -61,6 +61,7 @@ type knowledgeService struct {
docReaderClient *client.Client
chunkService interfaces.ChunkService
chunkRepo interfaces.ChunkRepository
tagRepo interfaces.KnowledgeTagRepository
fileSvc interfaces.FileService
modelService interfaces.ModelService
task *asynq.Client
@@ -81,6 +82,7 @@ func NewKnowledgeService(
tenantRepo interfaces.TenantRepository,
chunkService interfaces.ChunkService,
chunkRepo interfaces.ChunkRepository,
tagRepo interfaces.KnowledgeTagRepository,
fileSvc interfaces.FileService,
modelService interfaces.ModelService,
task *asynq.Client,
@@ -95,6 +97,7 @@ func NewKnowledgeService(
docReaderClient: docReaderClient,
chunkService: chunkService,
chunkRepo: chunkRepo,
tagRepo: tagRepo,
fileSvc: fileSvc,
modelService: modelService,
task: task,
@@ -2120,6 +2123,10 @@ func (s *knowledgeService) UpsertFAQEntries(ctx context.Context,
if err != nil {
return err
}
isEnabled := true
if entry.IsEnabled != nil {
isEnabled = *entry.IsEnabled
}
chunk := &types.Chunk{
ID: uuid.New().String(),
TenantID: tenantID,
@@ -2127,7 +2134,7 @@ func (s *knowledgeService) UpsertFAQEntries(ctx context.Context,
KnowledgeBaseID: kb.ID,
Content: buildFAQChunkContent(meta, indexMode),
ChunkIndex: startIndex + idx + 1,
IsEnabled: true,
IsEnabled: isEnabled,
ChunkType: types.ChunkTypeFAQ,
TagID: entry.TagID,
}
@@ -2191,10 +2198,30 @@ func (s *knowledgeService) UpdateFAQEntry(ctx context.Context,
}
chunk.Content = buildFAQChunkContent(meta, indexMode)
chunk.TagID = payload.TagID
isEnabledUpdated := false
if payload.IsEnabled != nil {
oldEnabled := chunk.IsEnabled
chunk.IsEnabled = *payload.IsEnabled
isEnabledUpdated = (oldEnabled != chunk.IsEnabled)
}
chunk.UpdatedAt = time.Now()
if err := s.chunkService.UpdateChunk(ctx, chunk); err != nil {
return err
}
// Sync is_enabled status to retriever engines if it was updated
if isEnabledUpdated {
chunkStatusMap := map[string]bool{chunk.ID: chunk.IsEnabled}
tenantInfo := ctx.Value(types.TenantInfoContextKey).(*types.Tenant)
retrieveEngine, err := retriever.NewCompositeRetrieveEngine(s.retrieveEngine, tenantInfo.RetrieverEngines.Engines)
if err != nil {
return err
}
if err := retrieveEngine.BatchUpdateChunkEnabledStatus(ctx, chunkStatusMap); err != nil {
return err
}
}
faqKnowledge, err := s.repo.GetKnowledgeByID(ctx, tenantID, chunk.KnowledgeID)
if err != nil {
return err
@@ -2202,6 +2229,312 @@ func (s *knowledgeService) UpdateFAQEntry(ctx context.Context,
return s.indexFAQChunks(ctx, kb, faqKnowledge, []*types.Chunk{chunk}, false)
}
// UpdateFAQEntryStatus updates enable status for a FAQ entry.
func (s *knowledgeService) UpdateFAQEntryStatus(ctx context.Context,
kbID string, entryID string, isEnabled bool,
) error {
kb, err := s.validateFAQKnowledgeBase(ctx, kbID)
if err != nil {
return err
}
tenantID := ctx.Value(types.TenantIDContextKey).(uint)
chunk, err := s.chunkRepo.GetChunkByID(ctx, tenantID, entryID)
if err != nil {
return err
}
if chunk.KnowledgeBaseID != kb.ID || chunk.ChunkType != types.ChunkTypeFAQ {
return werrors.NewBadRequestError("仅支持更新 FAQ 条目")
}
if chunk.IsEnabled == isEnabled {
return nil
}
chunk.IsEnabled = isEnabled
chunk.UpdatedAt = time.Now()
if err := s.chunkService.UpdateChunk(ctx, chunk); err != nil {
return err
}
// Sync update to retriever engines
chunkStatusMap := map[string]bool{chunk.ID: isEnabled}
tenantInfo := ctx.Value(types.TenantInfoContextKey).(*types.Tenant)
retrieveEngine, err := retriever.NewCompositeRetrieveEngine(s.retrieveEngine, tenantInfo.RetrieverEngines.Engines)
if err != nil {
return err
}
if err := retrieveEngine.BatchUpdateChunkEnabledStatus(ctx, chunkStatusMap); err != nil {
return err
}
return nil
}
// UpdateFAQEntryStatusBatch updates enable status for FAQ entries in batch.
func (s *knowledgeService) UpdateFAQEntryStatusBatch(ctx context.Context,
kbID string, updates map[string]bool,
) error {
if len(updates) == 0 {
return nil
}
kb, err := s.validateFAQKnowledgeBase(ctx, kbID)
if err != nil {
return err
}
tenantID := ctx.Value(types.TenantIDContextKey).(uint)
// 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
}
// 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
}
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 {
return err
}
chunkStatusMap[chunk.ID] = isEnabled
}
// Sync update to retriever engines
if len(chunkStatusMap) > 0 {
tenantInfo := ctx.Value(types.TenantInfoContextKey).(*types.Tenant)
retrieveEngine, err := retriever.NewCompositeRetrieveEngine(s.retrieveEngine, tenantInfo.RetrieverEngines.Engines)
if err != nil {
return err
}
if err := retrieveEngine.BatchUpdateChunkEnabledStatus(ctx, chunkStatusMap); err != nil {
return err
}
}
return nil
}
// UpdateKnowledgeTag updates the tag assigned to a knowledge document.
func (s *knowledgeService) UpdateKnowledgeTag(ctx context.Context, knowledgeID string, tagID *string) error {
tenantID := ctx.Value(types.TenantIDContextKey).(uint)
knowledge, err := s.repo.GetKnowledgeByID(ctx, tenantID, knowledgeID)
if err != nil {
return err
}
var resolvedTagID string
if tagID != nil && *tagID != "" {
tag, err := s.tagRepo.GetByID(ctx, tenantID, *tagID)
if err != nil {
return err
}
if tag.KnowledgeBaseID != knowledge.KnowledgeBaseID {
return werrors.NewBadRequestError("标签不属于当前知识库")
}
resolvedTagID = tag.ID
}
knowledge.TagID = resolvedTagID
return s.repo.UpdateKnowledge(ctx, knowledge)
}
// UpdateKnowledgeTagBatch updates tags for document knowledge items in batch.
func (s *knowledgeService) UpdateKnowledgeTagBatch(ctx context.Context, updates map[string]*string) error {
if len(updates) == 0 {
return nil
}
tenantID := ctx.Value(types.TenantIDContextKey).(uint)
// Get all knowledge items in batch
knowledgeIDs := make([]string, 0, len(updates))
for knowledgeID := range updates {
knowledgeIDs = append(knowledgeIDs, knowledgeID)
}
knowledgeList, err := s.repo.GetKnowledgeBatch(ctx, tenantID, knowledgeIDs)
if err != nil {
return err
}
// Build tag ID map for validation
tagIDSet := make(map[string]bool)
for _, tagID := range updates {
if tagID != nil && *tagID != "" {
tagIDSet[*tagID] = true
}
}
// Validate all tags in batch
tagMap := make(map[string]*types.KnowledgeTag)
if len(tagIDSet) > 0 {
tagIDs := make([]string, 0, len(tagIDSet))
for tagID := range tagIDSet {
tagIDs = append(tagIDs, tagID)
}
for _, tagID := range tagIDs {
tag, err := s.tagRepo.GetByID(ctx, tenantID, tagID)
if err != nil {
return err
}
tagMap[tagID] = tag
}
}
// Update knowledge items
knowledgeToUpdate := make([]*types.Knowledge, 0)
for _, knowledge := range knowledgeList {
tagID, exists := updates[knowledge.ID]
if !exists {
continue
}
var resolvedTagID string
if tagID != nil && *tagID != "" {
tag, ok := tagMap[*tagID]
if !ok {
return werrors.NewBadRequestError(fmt.Sprintf("标签 %s 不存在", *tagID))
}
if tag.KnowledgeBaseID != knowledge.KnowledgeBaseID {
return werrors.NewBadRequestError(fmt.Sprintf("标签 %s 不属于知识库 %s", *tagID, knowledge.KnowledgeBaseID))
}
resolvedTagID = tag.ID
}
knowledge.TagID = resolvedTagID
knowledgeToUpdate = append(knowledgeToUpdate, knowledge)
}
if len(knowledgeToUpdate) > 0 {
return s.repo.UpdateKnowledgeBatch(ctx, knowledgeToUpdate)
}
return nil
}
// UpdateFAQEntryTag updates the tag assigned to an FAQ entry.
func (s *knowledgeService) UpdateFAQEntryTag(ctx context.Context, kbID string, entryID string, tagID *string) error {
kb, err := s.validateFAQKnowledgeBase(ctx, kbID)
if err != nil {
return err
}
tenantID := ctx.Value(types.TenantIDContextKey).(uint)
chunk, err := s.chunkRepo.GetChunkByID(ctx, tenantID, entryID)
if err != nil {
return err
}
if chunk.KnowledgeBaseID != kb.ID || chunk.ChunkType != types.ChunkTypeFAQ {
return werrors.NewBadRequestError("仅支持更新 FAQ 条目标签")
}
var resolvedTagID string
if tagID != nil && *tagID != "" {
tag, err := s.tagRepo.GetByID(ctx, tenantID, *tagID)
if err != nil {
return err
}
if tag.KnowledgeBaseID != kb.ID {
return werrors.NewBadRequestError("标签不属于当前知识库")
}
resolvedTagID = tag.ID
}
chunk.TagID = resolvedTagID
chunk.UpdatedAt = time.Now()
return s.chunkRepo.UpdateChunk(ctx, chunk)
}
// UpdateFAQEntryTagBatch updates tags for FAQ entries in batch.
func (s *knowledgeService) UpdateFAQEntryTagBatch(ctx context.Context, kbID string, updates map[string]*string) error {
if len(updates) == 0 {
return nil
}
kb, err := s.validateFAQKnowledgeBase(ctx, kbID)
if err != nil {
return err
}
tenantID := ctx.Value(types.TenantIDContextKey).(uint)
// 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
}
// Build tag ID map for validation
tagIDSet := make(map[string]bool)
for _, tagID := range updates {
if tagID != nil && *tagID != "" {
tagIDSet[*tagID] = true
}
}
// Validate all tags in batch
tagMap := make(map[string]*types.KnowledgeTag)
if len(tagIDSet) > 0 {
tagIDs := make([]string, 0, len(tagIDSet))
for tagID := range tagIDSet {
tagIDs = append(tagIDs, tagID)
}
for _, tagID := range tagIDs {
tag, err := s.tagRepo.GetByID(ctx, tenantID, tagID)
if err != nil {
return err
}
if tag.KnowledgeBaseID != kb.ID {
return werrors.NewBadRequestError(fmt.Sprintf("标签 %s 不属于当前知识库", tagID))
}
tagMap[tagID] = tag
}
}
// Update chunks
chunksToUpdate := make([]*types.Chunk, 0)
for _, chunk := range chunks {
if chunk.KnowledgeBaseID != kb.ID || chunk.ChunkType != types.ChunkTypeFAQ {
continue
}
tagID, exists := updates[chunk.ID]
if !exists {
continue
}
var resolvedTagID string
if tagID != nil && *tagID != "" {
tag, ok := tagMap[*tagID]
if !ok {
return werrors.NewBadRequestError(fmt.Sprintf("标签 %s 不存在", *tagID))
}
resolvedTagID = tag.ID
}
chunk.TagID = resolvedTagID
chunk.UpdatedAt = time.Now()
chunksToUpdate = append(chunksToUpdate, chunk)
}
if len(chunksToUpdate) > 0 {
return s.chunkRepo.UpdateChunks(ctx, chunksToUpdate)
}
return nil
}
// SearchFAQEntries searches FAQ entries using hybrid search.
func (s *knowledgeService) SearchFAQEntries(ctx context.Context,
kbID string, req *types.FAQSearchRequest,
@@ -2268,6 +2601,9 @@ func (s *knowledgeService) SearchFAQEntries(ctx context.Context,
if chunk.ChunkType != types.ChunkTypeFAQ {
continue
}
if !chunk.IsEnabled {
continue
}
entry, err := s.chunkToFAQEntry(chunk, kb)
if err != nil {
@@ -2408,6 +2744,7 @@ func (s *knowledgeService) chunkToFAQEntry(chunk *types.Chunk, kb *types.Knowled
KnowledgeID: chunk.KnowledgeID,
KnowledgeBaseID: chunk.KnowledgeBaseID,
TagID: chunk.TagID,
IsEnabled: chunk.IsEnabled,
StandardQuestion: meta.StandardQuestion,
SimilarQuestions: meta.SimilarQuestions,
NegativeQuestions: meta.NegativeQuestions,
@@ -93,6 +93,16 @@ func (c *CompositeRetrieveEngine) SupportRetriever(r types.RetrieverType) bool {
return false
}
// BatchUpdateChunkEnabledStatus updates the enabled status of chunks in batch
func (c *CompositeRetrieveEngine) BatchUpdateChunkEnabledStatus(ctx context.Context, chunkStatusMap map[string]bool) error {
return c.concurrentExecWithError(ctx, func(ctx context.Context, engineInfo *engineInfo) error {
if err := engineInfo.retrieveEngine.BatchUpdateChunkEnabledStatus(ctx, chunkStatusMap); err != nil {
return err
}
return nil
})
}
// concurrentRetrieve is a helper function for concurrent processing of retrieval parameters
// and collecting results
func concurrentRetrieve(
@@ -161,3 +161,8 @@ func (v *KeywordsVectorHybridRetrieveEngineService) CopyIndices(
ctx, sourceKnowledgeBaseID, sourceToTargetKBIDMap, sourceToTargetChunkIDMap, targetKnowledgeBaseID, dimension,
)
}
// BatchUpdateChunkEnabledStatus updates the enabled status of chunks in batch
func (v *KeywordsVectorHybridRetrieveEngineService) BatchUpdateChunkEnabledStatus(ctx context.Context, chunkStatusMap map[string]bool) error {
return v.indexRepository.BatchUpdateChunkEnabledStatus(ctx, chunkStatusMap)
}
+46
View File
@@ -88,10 +88,56 @@ func (h *FAQHandler) UpdateEntry(c *gin.Context) {
})
}
// UpdateEntryTagBatch updates tags for FAQ entries in batch.
func (h *FAQHandler) UpdateEntryTagBatch(c *gin.Context) {
ctx := c.Request.Context()
var req faqEntryTagBatchRequest
if err := c.ShouldBindJSON(&req); err != nil {
logger.Error(ctx, "Failed to bind FAQ entry tag batch payload", err)
c.Error(errors.NewBadRequestError("请求参数不合法").WithDetails(err.Error()))
return
}
if err := h.knowledgeService.UpdateFAQEntryTagBatch(ctx, c.Param("id"), req.Updates); err != nil {
logger.ErrorWithFields(ctx, err, nil)
c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{
"success": true,
})
}
// UpdateEntryStatusBatch updates the enable status of FAQ entries in batch.
func (h *FAQHandler) UpdateEntryStatusBatch(c *gin.Context) {
ctx := c.Request.Context()
var req faqEntryStatusBatchRequest
if err := c.ShouldBindJSON(&req); err != nil {
logger.Error(ctx, "Failed to bind FAQ entry status batch payload", err)
c.Error(errors.NewBadRequestError("请求参数不合法").WithDetails(err.Error()))
return
}
if err := h.knowledgeService.UpdateFAQEntryStatusBatch(ctx, c.Param("id"), req.Updates); err != nil {
logger.ErrorWithFields(ctx, err, nil)
c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{
"success": true,
})
}
type faqDeleteRequest struct {
IDs []string `json:"ids" binding:"required,min=1,dive,required"`
}
type faqEntryStatusBatchRequest struct {
Updates map[string]bool `json:"updates" binding:"required,min=1"`
}
type faqEntryTagBatchRequest struct {
Updates map[string]*string `json:"updates" binding:"required,min=1"`
}
// DeleteEntries deletes FAQ entries in batch.
func (h *FAQHandler) DeleteEntries(c *gin.Context) {
ctx := c.Request.Context()
+2 -2
View File
@@ -223,7 +223,7 @@ func (h *InitializationHandler) UpdateKBConfig(c *gin.Context) {
kbIdStr, &types.Pagination{
Page: 1,
PageSize: 1,
})
}, "")
if err == nil && knowledgeList != nil && knowledgeList.Total > 0 {
logger.Error(ctx, "Cannot change embedding model when files exist")
c.Error(errors.NewBadRequestError("知识库中已有文件,无法修改Embedding模型"))
@@ -1129,7 +1129,7 @@ func (h *InitializationHandler) GetCurrentConfigByKB(c *gin.Context) {
kbIdStr, &types.Pagination{
Page: 1,
PageSize: 1,
})
}, "")
hasFiles := false
if err == nil && knowledgeList != nil && knowledgeList.Total > 0 {
hasFiles = true
+23
View File
@@ -509,6 +509,29 @@ func (h *KnowledgeHandler) UpdateManualKnowledge(c *gin.Context) {
})
}
type knowledgeTagBatchRequest struct {
Updates map[string]*string `json:"updates" binding:"required,min=1"`
}
// UpdateKnowledgeTagBatch updates tags for knowledge items in batch.
func (h *KnowledgeHandler) UpdateKnowledgeTagBatch(c *gin.Context) {
ctx := c.Request.Context()
var req knowledgeTagBatchRequest
if err := c.ShouldBindJSON(&req); err != nil {
logger.Error(ctx, "Failed to parse knowledge tag batch request", err)
c.Error(errors.NewBadRequestError("请求参数不合法").WithDetails(err.Error()))
return
}
if err := h.kgService.UpdateKnowledgeTagBatch(ctx, req.Updates); err != nil {
logger.ErrorWithFields(ctx, err, nil)
c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{
"success": true,
})
}
// UpdateImageInfo updates a chunk's properties
func (h *KnowledgeHandler) UpdateImageInfo(c *gin.Context) {
ctx := c.Request.Context()
+4
View File
@@ -148,6 +148,8 @@ func RegisterKnowledgeRoutes(r *gin.RouterGroup, handler *handler.KnowledgeHandl
k.GET("/:id/download", handler.DownloadKnowledgeFile)
// 更新图像分块信息
k.PUT("/image/:id/:chunk_id", handler.UpdateImageInfo)
// 批量更新知识标签
k.PUT("/tags", handler.UpdateKnowledgeTagBatch)
}
}
@@ -161,6 +163,8 @@ func RegisterFAQRoutes(r *gin.RouterGroup, handler *handler.FAQHandler) {
faq.GET("/entries", handler.ListEntries)
faq.POST("/entries", handler.UpsertEntries)
faq.PUT("/entries/:entry_id", handler.UpdateEntry)
faq.PUT("/entries/status", handler.UpdateEntryStatusBatch)
faq.PUT("/entries/tags", handler.UpdateEntryTagBatch)
faq.DELETE("/entries", handler.DeleteEntries)
faq.POST("/search", handler.SearchFAQ)
}
+2
View File
@@ -68,6 +68,7 @@ type FAQEntry struct {
KnowledgeID string `json:"knowledge_id"`
KnowledgeBaseID string `json:"knowledge_base_id"`
TagID string `json:"tag_id"`
IsEnabled bool `json:"is_enabled"`
StandardQuestion string `json:"standard_question"`
SimilarQuestions []string `json:"similar_questions"`
NegativeQuestions []string `json:"negative_questions"`
@@ -87,6 +88,7 @@ type FAQEntryPayload struct {
NegativeQuestions []string `json:"negative_questions"`
Answers []string `json:"answers" binding:"required"`
TagID string `json:"tag_id"`
IsEnabled *bool `json:"is_enabled,omitempty"`
}
const (
+2
View File
@@ -29,6 +29,8 @@ type ChunkRepository interface {
ListChunkByParentID(ctx context.Context, tenantID uint, parentID string) ([]*types.Chunk, 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, tenantID uint, id string) error
// DeleteChunksByKnowledgeID deletes chunks by knowledge id
+8
View File
@@ -59,10 +59,16 @@ type KnowledgeService interface {
UpsertFAQEntries(ctx context.Context, kbID string, payload *types.FAQBatchUpsertPayload) error
// UpdateFAQEntry updates a single FAQ entry.
UpdateFAQEntry(ctx context.Context, kbID string, entryID string, payload *types.FAQEntryPayload) error
// UpdateFAQEntryStatusBatch updates enable status for FAQ entries in batch.
UpdateFAQEntryStatusBatch(ctx context.Context, kbID string, updates map[string]bool) error
// DeleteFAQEntries deletes FAQ entries in batch.
DeleteFAQEntries(ctx context.Context, kbID string, entryIDs []string) error
// SearchFAQEntries searches FAQ entries using hybrid search.
SearchFAQEntries(ctx context.Context, kbID string, req *types.FAQSearchRequest) ([]*types.FAQEntry, error)
// UpdateKnowledgeTagBatch updates tag for document knowledge items in batch.
UpdateKnowledgeTagBatch(ctx context.Context, updates map[string]*string) error
// UpdateFAQEntryTagBatch updates tag for FAQ entries in batch.
UpdateFAQEntryTagBatch(ctx context.Context, kbID string, updates map[string]*string) error
}
// KnowledgeRepository defines the interface for knowledge repositories.
@@ -76,6 +82,8 @@ type KnowledgeRepository interface {
tenantID uint, kbID string, page *types.Pagination, tagID string,
) ([]*types.Knowledge, int64, error)
UpdateKnowledge(ctx context.Context, knowledge *types.Knowledge) error
// UpdateKnowledgeBatch updates knowledge items in batch
UpdateKnowledgeBatch(ctx context.Context, knowledgeList []*types.Knowledge) error
DeleteKnowledge(ctx context.Context, tenantID uint, id string) error
DeleteKnowledgeList(ctx context.Context, tenantID uint, ids []string) error
GetKnowledgeBatch(ctx context.Context, tenantID uint, ids []string) ([]*types.Knowledge, error)
+8
View File
@@ -49,6 +49,10 @@ type RetrieveEngineRepository interface {
// DeleteByKnowledgeIDList deletes the index info by knowledge id list
DeleteByKnowledgeIDList(ctx context.Context, knowledgeIDList []string, dimension int) error
// BatchUpdateChunkEnabledStatus updates the enabled status of chunks in batch
// chunkStatusMap: map of chunk ID to enabled status (true = enabled, false = disabled)
BatchUpdateChunkEnabledStatus(ctx context.Context, chunkStatusMap map[string]bool) error
// RetrieveEngine retrieves the engine
RetrieveEngine
}
@@ -104,6 +108,10 @@ type RetrieveEngineService interface {
// DeleteByKnowledgeIDList deletes the index info by knowledge id list
DeleteByKnowledgeIDList(ctx context.Context, knowledgeIDList []string, dimension int) error
// BatchUpdateChunkEnabledStatus updates the enabled status of chunks in batch
// chunkStatusMap: map of chunk ID to enabled status (true = enabled, false = disabled)
BatchUpdateChunkEnabledStatus(ctx context.Context, chunkStatusMap map[string]bool) error
// RetrieveEngine retrieves the engine
RetrieveEngine
}
@@ -0,0 +1,14 @@
-- 000010_add_embeddings_is_enabled.down.sql
-- Remove is_enabled column from embeddings table
BEGIN;
-- Drop index
DROP INDEX IF EXISTS idx_embeddings_is_enabled;
-- Remove is_enabled column
ALTER TABLE embeddings
DROP COLUMN IF EXISTS is_enabled;
COMMIT;
@@ -0,0 +1,15 @@
-- 000010_add_embeddings_is_enabled.up.sql
-- Add is_enabled column to embeddings table
BEGIN;
-- Add is_enabled column to embeddings table
ALTER TABLE embeddings
ADD COLUMN IF NOT EXISTS is_enabled BOOLEAN DEFAULT TRUE;
-- Create index for is_enabled column
CREATE INDEX IF NOT EXISTS idx_embeddings_is_enabled
ON embeddings(is_enabled);
COMMIT;