|
|
@@ -8,11 +8,11 @@ import com.zsjz.ai.common.exception.ServerException;
|
|
|
import com.zsjz.ai.common.model.plat.entity.TableField;
|
|
|
import com.zsjz.ai.common.model.plat.entity.TableInfo;
|
|
|
import com.zsjz.ai.common.utils.Json;
|
|
|
+import com.zsjz.ai.common.vector.ZvecVectorStore;
|
|
|
import com.zsjz.ai.module.aiclean.entity.AiCleanField;
|
|
|
import com.zsjz.ai.module.aiclean.entity.AiCleanTemplate;
|
|
|
import com.zsjz.ai.module.aiclean.mapper.AiCleanFieldMapper;
|
|
|
import com.zsjz.ai.module.aiclean.mapper.AiCleanTemplateMapper;
|
|
|
-import com.zsjz.ai.module.aiclean.mapper.AiCleanVectorMapper;
|
|
|
import com.zsjz.ai.module.embedding.service.EmbeddingProvider;
|
|
|
import com.zsjz.ai.module.plat.mapper.TableFieldMapper;
|
|
|
import com.zsjz.ai.module.plat.mapper.TableInfoMapper;
|
|
|
@@ -26,30 +26,30 @@ import java.util.ArrayList;
|
|
|
import java.util.LinkedHashMap;
|
|
|
import java.util.List;
|
|
|
import java.util.Map;
|
|
|
-import java.util.Set;
|
|
|
-import java.util.concurrent.ConcurrentHashMap;
|
|
|
import java.util.concurrent.ExecutorService;
|
|
|
import java.util.concurrent.Executors;
|
|
|
|
|
|
/**
|
|
|
* 模板结构向量索引:把两套模板库(既有 {@code table_info}/{@code table_field} 与
|
|
|
* AI 侧 {@code ai_clean_template}/{@code ai_clean_field})的结构元数据嵌入成向量,
|
|
|
- * 存进全局 pgvector 表,服务「AI 模板识别语义召回」。
|
|
|
+ * 存进进程内 zvec collection,服务「AI 模板识别语义召回」。
|
|
|
*
|
|
|
- * <h3>一张全局表</h3>
|
|
|
+ * <h3>全局一个 collection</h3>
|
|
|
* 事实来源只有两套模板元数据(<b>不扫描案件 DuckDB</b>),模板是全局资产,
|
|
|
- * 所以索引也只建一张表 {@code rag_tpl{modelTag}_d{dims}}:
|
|
|
+ * 所以索引也只建一个 collection {@code rag_tpl{modelTag}_d{dims}}(落在
|
|
|
+ * {@code qingjian/system/vector} 下,<b>不按案件隔离</b>):
|
|
|
* {@link #recall} 做候选语义召回(只影响候选排序,不参与判档)。
|
|
|
*
|
|
|
* <h3>什么时候建</h3>
|
|
|
* 模板新增 / 更新 / 删除时由 {@link TemplateMetaChangedEvent} 触发增量更新(异步、fail-open);
|
|
|
* 存量数据与模型切换走 {@link #rebuildNow()} / {@link #rebuildAsync()} 全量重建;
|
|
|
- * 应用启动后若索引表不存在或为空,按 {@code autoRebuildOnStartup} 后台自举一次
|
|
|
+ * 应用启动后若 collection 不存在或为空,按 {@code autoRebuildOnStartup} 后台自举一次
|
|
|
* (见 {@link #onApplicationReady})—— 存量模板不会补发变更事件,没有自举就必须人工调重建接口。
|
|
|
*
|
|
|
* <h3>失败语义</h3>
|
|
|
- * 全链路 fail-open:未配置嵌入模型、pgvector 不可用、嵌入调用超时……一律降级为「没有召回」,
|
|
|
- * 绝不把异常抛回上传 / 清洗线程 —— 模板识别的主链路(指纹 → 打分 → LLM)不依赖向量。
|
|
|
+ * 全链路 fail-open:未配置嵌入模型、zvec 原生库不可用、目录被其他进程锁定、嵌入调用超时……
|
|
|
+ * 一律降级为「没有召回」,绝不把异常抛回上传 / 清洗线程 —— 模板识别的主链路
|
|
|
+ * (指纹 → 打分 → LLM)不依赖向量。
|
|
|
*
|
|
|
* @author cc
|
|
|
* @since 2026/10/19
|
|
|
@@ -64,14 +64,14 @@ public class AiCleanTemplateVectorIndex {
|
|
|
/** AI 模板库文档类型 */
|
|
|
public static final String KIND_AI = "AI";
|
|
|
|
|
|
- /** 向量表名前缀;完整表名 = rag_tpl{tag}_d{dims}(按维度/模型隔离,换模型后自然重建) */
|
|
|
- static final String VECTOR_TABLE_PREFIX = "rag_tpl";
|
|
|
+ /** collection 名前缀;完整名字 = rag_tpl{tag}_d{dims}(按维度/模型隔离,换模型后自然重建) */
|
|
|
+ static final String VECTOR_COLLECTION_PREFIX = "rag_tpl";
|
|
|
|
|
|
/**
|
|
|
* 全量重建时「连续失败」熔断阈值。
|
|
|
*
|
|
|
* <p>单条失败(维度不符、个别文本超长)可以跳过继续;但连续 5 条都失败,通常是嵌入模型 / API Key
|
|
|
- * 不可用或 pgvector 写不进去 —— 这时逐条重试只会把日志刷爆、把重建拖到天荒地老,不如尽早中止。
|
|
|
+ * 不可用或 zvec 写不进去 —— 这时逐条重试只会把日志刷爆、把重建拖到天荒地老,不如尽早中止。
|
|
|
*/
|
|
|
static final int MAX_CONSECUTIVE_FAILURES = 5;
|
|
|
|
|
|
@@ -83,14 +83,14 @@ public class AiCleanTemplateVectorIndex {
|
|
|
|
|
|
private final AiCleanVectorProperties properties;
|
|
|
private final EmbeddingProvider embeddingProvider;
|
|
|
- private final AiCleanVectorMapper aiCleanVectorMapper;
|
|
|
+ private final ZvecVectorStore vectorStore;
|
|
|
private final TableInfoMapper tableInfoMapper;
|
|
|
private final TableFieldMapper tableFieldMapper;
|
|
|
private final AiCleanTemplateMapper aiCleanTemplateMapper;
|
|
|
private final AiCleanFieldMapper aiCleanFieldMapper;
|
|
|
|
|
|
/**
|
|
|
- * 单线程守护线程池:增量索引串行执行,避免同一 docId 并发写 / 多次建表竞态。
|
|
|
+ * 单线程守护线程池:增量索引串行执行,避免同一 docId 并发写 / 多次建 collection 竞态。
|
|
|
*/
|
|
|
private final ExecutorService executor = Executors.newSingleThreadExecutor(r -> {
|
|
|
Thread t = new Thread(r, "ai-tpl-vector");
|
|
|
@@ -98,27 +98,19 @@ public class AiCleanTemplateVectorIndex {
|
|
|
return t;
|
|
|
});
|
|
|
|
|
|
- /** 全量重建互斥:重建会 DROP 整表,两个并发的 rebuild 必须串行(SQL 侧不能靠 IF NOT EXISTS 兜住) */
|
|
|
+ /** 全量重建互斥:重建会删掉整个 collection,两个并发的 rebuild 必须串行 */
|
|
|
private final Object rebuildLock = new Object();
|
|
|
|
|
|
- /**
|
|
|
- * 当前进程已确认存在的向量表。
|
|
|
- *
|
|
|
- * <p>增量写逐条执行,如果每条都先查 {@code information_schema} 就是一次多余往返;
|
|
|
- * 建表后记住表名,后续同维度的写入直接跳过探测。
|
|
|
- */
|
|
|
- private final Set<String> ensuredVectorTables = ConcurrentHashMap.newKeySet();
|
|
|
-
|
|
|
public AiCleanTemplateVectorIndex(AiCleanVectorProperties properties,
|
|
|
EmbeddingProvider embeddingProvider,
|
|
|
- AiCleanVectorMapper aiCleanVectorMapper,
|
|
|
+ ZvecVectorStore vectorStore,
|
|
|
TableInfoMapper tableInfoMapper,
|
|
|
TableFieldMapper tableFieldMapper,
|
|
|
AiCleanTemplateMapper aiCleanTemplateMapper,
|
|
|
AiCleanFieldMapper aiCleanFieldMapper) {
|
|
|
this.properties = properties;
|
|
|
this.embeddingProvider = embeddingProvider;
|
|
|
- this.aiCleanVectorMapper = aiCleanVectorMapper;
|
|
|
+ this.vectorStore = vectorStore;
|
|
|
this.tableInfoMapper = tableInfoMapper;
|
|
|
this.tableFieldMapper = tableFieldMapper;
|
|
|
this.aiCleanTemplateMapper = aiCleanTemplateMapper;
|
|
|
@@ -126,14 +118,14 @@ public class AiCleanTemplateVectorIndex {
|
|
|
}
|
|
|
|
|
|
/**
|
|
|
- * 向量索引是否可用:开关打开且本地嵌入模型可用。
|
|
|
+ * 向量索引是否可用:开关打开、本地嵌入模型可用且 zvec 原生库可加载。
|
|
|
*/
|
|
|
public boolean isAvailable() {
|
|
|
if (!properties.isEnabled()) {
|
|
|
return false;
|
|
|
}
|
|
|
try {
|
|
|
- return embeddingProvider.isAvailable();
|
|
|
+ return embeddingProvider.isAvailable() && vectorStore.isAvailable();
|
|
|
} catch (Exception e) {
|
|
|
// 再兜一层是因为 mock / 未来实现都可能抛,召回链路上不允许它冒泡
|
|
|
log.error("判断 AI 模板向量索引可用性失败(按不可用处理): {}", e.getMessage());
|
|
|
@@ -145,7 +137,13 @@ public class AiCleanTemplateVectorIndex {
|
|
|
* 当前向量模型不可用的原因(供接口层给出可操作提示)。
|
|
|
*/
|
|
|
public String unavailableMessage() {
|
|
|
- return embeddingProvider.unavailableMessage();
|
|
|
+ if (!properties.isEnabled()) {
|
|
|
+ return "AI 模板向量索引未启用(zsjz.ai-clean.vector.enabled=false)";
|
|
|
+ }
|
|
|
+ if (!embeddingProvider.isAvailable()) {
|
|
|
+ return embeddingProvider.unavailableMessage();
|
|
|
+ }
|
|
|
+ return vectorStore.unavailableMessage();
|
|
|
}
|
|
|
|
|
|
/**
|
|
|
@@ -202,13 +200,13 @@ public class AiCleanTemplateVectorIndex {
|
|
|
}
|
|
|
|
|
|
/**
|
|
|
- * 启动自举:应用就绪时若向量表不存在或为空,后台全量重建一次。
|
|
|
+ * 启动自举:应用就绪时若 collection 不存在或为空,后台全量重建一次。
|
|
|
*
|
|
|
* <p><b>为什么需要</b>:模板变更事件只会覆盖「升级后新发生的写入」,存量模板不会补发事件;
|
|
|
* 没有自举的话,升级后必须人工调一次 {@code /aiClean/templateVector/rebuild},
|
|
|
- * 否则 {@code search_table_schema} 永远检索不到东西、模板匹配也永远没有向量召回。
|
|
|
+ * 否则模板匹配永远没有向量召回。
|
|
|
*
|
|
|
- * <p><b>fail-open</b>:模型未配置、PG 未装 pgvector、表探测失败……一律只记日志,
|
|
|
+ * <p><b>fail-open</b>:模型未配置、zvec 原生库不可用、目录被锁……一律只记日志,
|
|
|
* 绝不让启动失败 —— 索引是增强能力,不是应用能否运行的前提。
|
|
|
* 重建动作本身走 {@link #rebuildAsync()}(异步 + 内部有连续失败熔断),不会拖慢启动。
|
|
|
*/
|
|
|
@@ -219,7 +217,7 @@ public class AiCleanTemplateVectorIndex {
|
|
|
}
|
|
|
try {
|
|
|
if (!isAvailable()) {
|
|
|
- log.info("启动自举跳过模板向量索引:{}", embeddingProvider.unavailableMessage());
|
|
|
+ log.info("启动自举跳过模板向量索引:{}", unavailableMessage());
|
|
|
return;
|
|
|
}
|
|
|
int dimensions = embeddingProvider.dimensions();
|
|
|
@@ -228,8 +226,8 @@ public class AiCleanTemplateVectorIndex {
|
|
|
return;
|
|
|
}
|
|
|
String vectorTable = vectorTableName(embeddingProvider.tableTag(), dimensions);
|
|
|
- boolean empty = !vectorTableExists(vectorTable)
|
|
|
- || aiCleanVectorMapper.countVectorDocs(vectorTable) == 0;
|
|
|
+ boolean empty = !vectorStore.collectionExists(vectorTable)
|
|
|
+ || vectorStore.count(vectorTable) == 0;
|
|
|
if (!empty) {
|
|
|
log.debug("启动自举跳过模板向量索引:{} 已有数据", vectorTable);
|
|
|
return;
|
|
|
@@ -242,12 +240,12 @@ public class AiCleanTemplateVectorIndex {
|
|
|
}
|
|
|
|
|
|
/**
|
|
|
- * 同步全量重建:DROP 后重写两套模板库的全部文档。
|
|
|
+ * 同步全量重建:删掉 collection 后重写两套模板库的全部文档。
|
|
|
*
|
|
|
- * <p>先构建完整文档清单再动表:读库失败时旧的向量表还在,索引不会因为一次失败被清空。
|
|
|
+ * <p>先构建完整文档清单再动 collection:读库失败时旧索引还在,不会因为一次失败被清空。
|
|
|
*
|
|
|
* @return 实际写入的文档数(嵌入失败 / 维度不符的文档被跳过,不计入)
|
|
|
- * @throws ServerException 开关关闭、向量模型不可用或建表 / 写库失败时
|
|
|
+ * @throws ServerException 开关关闭、向量模型不可用或建 collection / 写库失败时
|
|
|
*/
|
|
|
public int rebuildNow() {
|
|
|
if (!properties.isEnabled()) {
|
|
|
@@ -256,6 +254,9 @@ public class AiCleanTemplateVectorIndex {
|
|
|
if (!embeddingProvider.isAvailable()) {
|
|
|
throw new ServerException(400, embeddingProvider.unavailableMessage());
|
|
|
}
|
|
|
+ if (!vectorStore.isAvailable()) {
|
|
|
+ throw new ServerException(400, vectorStore.unavailableMessage());
|
|
|
+ }
|
|
|
int dimensions = embeddingProvider.dimensions();
|
|
|
if (dimensions <= 0) {
|
|
|
throw new ServerException(500, "嵌入模型维度无效: " + dimensions);
|
|
|
@@ -271,9 +272,8 @@ public class AiCleanTemplateVectorIndex {
|
|
|
total, max);
|
|
|
docs = docs.subList(0, max);
|
|
|
}
|
|
|
- aiCleanVectorMapper.dropVectorTable(vectorTable);
|
|
|
- aiCleanVectorMapper.createVectorTableIfNotExists(vectorTable, dimensions);
|
|
|
- ensuredVectorTables.add(vectorTable);
|
|
|
+ vectorStore.dropCollection(vectorTable);
|
|
|
+ vectorStore.createCollectionIfNotExists(vectorTable, dimensions);
|
|
|
int written = 0;
|
|
|
// 连续失败熔断:embedding 连续失败到阈值就中止本次重建(返回已写入数),
|
|
|
// 通常是模型不可用,继续逐条重试只会刷屏且拖长重建时间
|
|
|
@@ -284,12 +284,16 @@ public class AiCleanTemplateVectorIndex {
|
|
|
consecutiveFailures = 0;
|
|
|
} else if (++consecutiveFailures >= MAX_CONSECUTIVE_FAILURES) {
|
|
|
log.error("AI 模板向量全量重建连续 {} 次写入失败,已中止(已写入 {} 条)。"
|
|
|
- + "请检查本地嵌入模型目录(zsjz.embedding.model-path)或 pgvector 是否可用",
|
|
|
+ + "请检查本地嵌入模型目录(zsjz.embedding.model-path)或 zvec 是否可用",
|
|
|
consecutiveFailures, written);
|
|
|
break;
|
|
|
}
|
|
|
}
|
|
|
- log.info("AI 模板向量全量重建完成: table={}, dims={}, docs={}/{}(截断前 {})",
|
|
|
+ if (written > 0) {
|
|
|
+ vectorStore.flush(vectorTable);
|
|
|
+ vectorStore.optimize(vectorTable);
|
|
|
+ }
|
|
|
+ log.info("AI 模板向量全量重建完成: collection={}, dims={}, docs={}/{}(截断前 {})",
|
|
|
vectorTable, dimensions, written, docs.size(), total);
|
|
|
return written;
|
|
|
} catch (ServerException e) {
|
|
|
@@ -314,7 +318,7 @@ public class AiCleanTemplateVectorIndex {
|
|
|
return List.of();
|
|
|
}
|
|
|
try {
|
|
|
- if (!embeddingProvider.isAvailable()) {
|
|
|
+ if (!embeddingProvider.isAvailable() || !vectorStore.isAvailable()) {
|
|
|
return List.of();
|
|
|
}
|
|
|
int limit = topK > 0 ? topK : properties.getTopK();
|
|
|
@@ -326,7 +330,7 @@ public class AiCleanTemplateVectorIndex {
|
|
|
return List.of();
|
|
|
}
|
|
|
String vectorTable = vectorTableName(embeddingProvider.tableTag(), dimensions);
|
|
|
- if (!vectorTableExists(vectorTable)) {
|
|
|
+ if (!vectorStore.collectionExists(vectorTable)) {
|
|
|
// 还没索引过(刚部署 / 从没 rebuild):直接按无召回处理,别让调用方等一次空查询异常
|
|
|
return List.of();
|
|
|
}
|
|
|
@@ -334,22 +338,19 @@ public class AiCleanTemplateVectorIndex {
|
|
|
if (queryVector == null) {
|
|
|
return List.of();
|
|
|
}
|
|
|
- List<Map<String, Object>> rows = aiCleanVectorMapper.searchVector(vectorTable,
|
|
|
- toVectorLiteral(queryVector), properties.getScoreThreshold(), limit,
|
|
|
+ List<ZvecVectorStore.SearchHit> rows = vectorStore.search(vectorTable,
|
|
|
+ toFloatArray(queryVector), properties.getScoreThreshold(), limit,
|
|
|
// 模板识别只看模板文档
|
|
|
List.of(KIND_TABLE, KIND_AI));
|
|
|
if (rows == null || rows.isEmpty()) {
|
|
|
return List.of();
|
|
|
}
|
|
|
List<VectorHit> hits = new ArrayList<>(rows.size());
|
|
|
- for (Map<String, Object> row : rows) {
|
|
|
+ for (ZvecVectorStore.SearchHit row : rows) {
|
|
|
if (row == null) {
|
|
|
continue;
|
|
|
}
|
|
|
- Object payload = row.get("payload");
|
|
|
- Object score = row.get("score");
|
|
|
- VectorHit hit = toHit(payload == null ? null : payload.toString(),
|
|
|
- score instanceof Number n ? n.doubleValue() : 0.0);
|
|
|
+ VectorHit hit = toHit(row.payload(), row.score());
|
|
|
if (hit != null) {
|
|
|
hits.add(hit);
|
|
|
}
|
|
|
@@ -366,12 +367,12 @@ public class AiCleanTemplateVectorIndex {
|
|
|
*/
|
|
|
public IndexStatus status() {
|
|
|
try {
|
|
|
- // 开关关闭时直接返回:否则会去探测 pgvector 专有方言的向量表,
|
|
|
- // 在 SQLite 主库上必然失败,虽然被吞掉但每次调用都刷一条 debug 噪音。
|
|
|
+ // 开关关闭时直接返回:否则会触发 zvec 原生库加载与目录探测,
|
|
|
+ // 无向量场景下每次状态查询都白跑一次
|
|
|
if (!properties.isEnabled()) {
|
|
|
return new IndexStatus(false, null, null, 0, 0L);
|
|
|
}
|
|
|
- if (!embeddingProvider.isAvailable()) {
|
|
|
+ if (!embeddingProvider.isAvailable() || !vectorStore.isAvailable()) {
|
|
|
return new IndexStatus(false, null, null, 0, 0L);
|
|
|
}
|
|
|
int dimensions = embeddingProvider.dimensions();
|
|
|
@@ -381,11 +382,11 @@ public class AiCleanTemplateVectorIndex {
|
|
|
String vectorTable = vectorTableName(embeddingProvider.tableTag(), dimensions);
|
|
|
long docCount = 0L;
|
|
|
try {
|
|
|
- if (vectorTableExists(vectorTable)) {
|
|
|
- docCount = aiCleanVectorMapper.countVectorDocs(vectorTable);
|
|
|
+ if (vectorStore.collectionExists(vectorTable)) {
|
|
|
+ docCount = vectorStore.count(vectorTable);
|
|
|
}
|
|
|
} catch (Exception e) {
|
|
|
- log.debug("读取模板向量表行数失败(状态按 0 处理): {}", e.getMessage());
|
|
|
+ log.debug("读取模板向量 collection 文档数失败(状态按 0 处理): {}", e.getMessage());
|
|
|
}
|
|
|
return new IndexStatus(properties.isEnabled(), vectorTable, embeddingProvider.modelName(),
|
|
|
dimensions, docCount);
|
|
|
@@ -440,33 +441,41 @@ public class AiCleanTemplateVectorIndex {
|
|
|
* 与 {@code TemplateCandidateLoader#fromSettingLib}「无字段的模板不参与匹配」口径保持一致。
|
|
|
*/
|
|
|
int indexTableNow(Integer tableId) {
|
|
|
- try {
|
|
|
- if (!embeddingProvider.isAvailable()) {
|
|
|
- log.debug("嵌入模型不可用,跳过既有模板向量索引: tableId={}", tableId);
|
|
|
- return 0;
|
|
|
- }
|
|
|
- int dimensions = embeddingProvider.dimensions();
|
|
|
- if (dimensions <= 0) {
|
|
|
- return 0;
|
|
|
- }
|
|
|
- String docId = DOC_ID_TABLE_PREFIX + tableId;
|
|
|
- String vectorTable = vectorTableName(embeddingProvider.tableTag(), dimensions);
|
|
|
- TableInfo table = tableInfoMapper.selectById(tableId);
|
|
|
- if (table == null) {
|
|
|
- removeDoc(vectorTable, docId);
|
|
|
- return 0;
|
|
|
- }
|
|
|
- List<TableField> fields = loadTableFields(table);
|
|
|
- if (fields.isEmpty()) {
|
|
|
- removeDoc(vectorTable, docId);
|
|
|
+ // 与 rebuildNow 共用同一把锁:同步重建(接口线程)和异步增量(单线程池)不能交错,
|
|
|
+ // 否则 rebuild 删掉 collection 时,增量那条写入会落到错误/已关闭的句柄上
|
|
|
+ synchronized (rebuildLock) {
|
|
|
+ try {
|
|
|
+ if (!embeddingProvider.isAvailable() || !vectorStore.isAvailable()) {
|
|
|
+ log.debug("嵌入模型或 zvec 不可用,跳过既有模板向量索引: tableId={}", tableId);
|
|
|
+ return 0;
|
|
|
+ }
|
|
|
+ int dimensions = embeddingProvider.dimensions();
|
|
|
+ if (dimensions <= 0) {
|
|
|
+ return 0;
|
|
|
+ }
|
|
|
+ String docId = DOC_ID_TABLE_PREFIX + tableId;
|
|
|
+ String vectorTable = vectorTableName(embeddingProvider.tableTag(), dimensions);
|
|
|
+ TableInfo table = tableInfoMapper.selectById(tableId);
|
|
|
+ if (table == null) {
|
|
|
+ removeDoc(vectorTable, docId);
|
|
|
+ return 0;
|
|
|
+ }
|
|
|
+ List<TableField> fields = loadTableFields(table);
|
|
|
+ if (fields.isEmpty()) {
|
|
|
+ removeDoc(vectorTable, docId);
|
|
|
+ return 0;
|
|
|
+ }
|
|
|
+ vectorStore.createCollectionIfNotExists(vectorTable, dimensions);
|
|
|
+ int written = writeDoc(vectorTable, dimensions, buildTableDoc(table, fields)) ? 1 : 0;
|
|
|
+ if (written > 0) {
|
|
|
+ vectorStore.flush(vectorTable);
|
|
|
+ }
|
|
|
+ return written;
|
|
|
+ } catch (Exception e) {
|
|
|
+ log.error("增量索引既有模板失败(已降级,不影响清洗主流程): tableId={}, error={}",
|
|
|
+ tableId, e.getMessage());
|
|
|
return 0;
|
|
|
}
|
|
|
- ensureVectorTable(vectorTable, dimensions);
|
|
|
- return writeDoc(vectorTable, dimensions, buildTableDoc(table, fields)) ? 1 : 0;
|
|
|
- } catch (Exception e) {
|
|
|
- log.error("增量索引既有模板失败(已降级,不影响清洗主流程): tableId={}, error={}",
|
|
|
- tableId, e.getMessage());
|
|
|
- return 0;
|
|
|
}
|
|
|
}
|
|
|
|
|
|
@@ -479,70 +488,80 @@ public class AiCleanTemplateVectorIndex {
|
|
|
* 已删除的模板(查不到)与没有字段的模板按删除处理(旧向量是脏数据)。
|
|
|
*/
|
|
|
int indexAiTemplateNow(Long aiTemplateId) {
|
|
|
- try {
|
|
|
- if (!embeddingProvider.isAvailable()) {
|
|
|
- log.debug("嵌入模型不可用,跳过 AI 模板向量索引: aiTemplateId={}", aiTemplateId);
|
|
|
- return 0;
|
|
|
- }
|
|
|
- int dimensions = embeddingProvider.dimensions();
|
|
|
- if (dimensions <= 0) {
|
|
|
- return 0;
|
|
|
- }
|
|
|
- String docId = DOC_ID_AI_PREFIX + aiTemplateId;
|
|
|
- String vectorTable = vectorTableName(embeddingProvider.tableTag(), dimensions);
|
|
|
- AiCleanTemplate template = aiCleanTemplateMapper.selectById(aiTemplateId);
|
|
|
- if (template == null) {
|
|
|
- removeDoc(vectorTable, docId);
|
|
|
- return 0;
|
|
|
- }
|
|
|
- List<AiCleanField> fields = aiCleanFieldMapper.selectList(
|
|
|
- Wrappers.<AiCleanField>lambdaQuery()
|
|
|
- .eq(AiCleanField::getAiTemplateId, aiTemplateId)
|
|
|
- .orderByAsc(AiCleanField::getFieldSort)
|
|
|
- .orderByAsc(AiCleanField::getId));
|
|
|
- if (fields == null || fields.isEmpty()) {
|
|
|
- // 无字段的模板既不能匹配也不能被选表,按删除处理(与全量重建口径一致)
|
|
|
- removeDoc(vectorTable, docId);
|
|
|
+ // 同 indexTableNow:与 rebuildNow 串行,避免重建删 collection 与增量写入交错
|
|
|
+ synchronized (rebuildLock) {
|
|
|
+ try {
|
|
|
+ if (!embeddingProvider.isAvailable() || !vectorStore.isAvailable()) {
|
|
|
+ log.debug("嵌入模型或 zvec 不可用,跳过 AI 模板向量索引: aiTemplateId={}", aiTemplateId);
|
|
|
+ return 0;
|
|
|
+ }
|
|
|
+ int dimensions = embeddingProvider.dimensions();
|
|
|
+ if (dimensions <= 0) {
|
|
|
+ return 0;
|
|
|
+ }
|
|
|
+ String docId = DOC_ID_AI_PREFIX + aiTemplateId;
|
|
|
+ String vectorTable = vectorTableName(embeddingProvider.tableTag(), dimensions);
|
|
|
+ AiCleanTemplate template = aiCleanTemplateMapper.selectById(aiTemplateId);
|
|
|
+ if (template == null) {
|
|
|
+ removeDoc(vectorTable, docId);
|
|
|
+ return 0;
|
|
|
+ }
|
|
|
+ List<AiCleanField> fields = aiCleanFieldMapper.selectList(
|
|
|
+ Wrappers.<AiCleanField>lambdaQuery()
|
|
|
+ .eq(AiCleanField::getAiTemplateId, aiTemplateId)
|
|
|
+ .orderByAsc(AiCleanField::getFieldSort)
|
|
|
+ .orderByAsc(AiCleanField::getId));
|
|
|
+ if (fields == null || fields.isEmpty()) {
|
|
|
+ // 无字段的模板既不能匹配也不能被选表,按删除处理(与全量重建口径一致)
|
|
|
+ removeDoc(vectorTable, docId);
|
|
|
+ return 0;
|
|
|
+ }
|
|
|
+ vectorStore.createCollectionIfNotExists(vectorTable, dimensions);
|
|
|
+ int written = writeDoc(vectorTable, dimensions, buildAiDoc(template, fields)) ? 1 : 0;
|
|
|
+ if (written > 0) {
|
|
|
+ vectorStore.flush(vectorTable);
|
|
|
+ }
|
|
|
+ return written;
|
|
|
+ } catch (Exception e) {
|
|
|
+ log.error("增量索引 AI 模板失败(已降级,不影响清洗主流程): aiTemplateId={}, error={}",
|
|
|
+ aiTemplateId, e.getMessage());
|
|
|
return 0;
|
|
|
}
|
|
|
- ensureVectorTable(vectorTable, dimensions);
|
|
|
- return writeDoc(vectorTable, dimensions, buildAiDoc(template, fields)) ? 1 : 0;
|
|
|
- } catch (Exception e) {
|
|
|
- log.error("增量索引 AI 模板失败(已降级,不影响清洗主流程): aiTemplateId={}, error={}",
|
|
|
- aiTemplateId, e.getMessage());
|
|
|
- return 0;
|
|
|
}
|
|
|
}
|
|
|
|
|
|
/**
|
|
|
- * 删除单条文档(表不存在时视为「本来就没有」,不记 warn)。
|
|
|
+ * 删除单条文档(collection 不存在时视为「本来就没有」,不记 warn)。
|
|
|
*/
|
|
|
private void removeDoc(String docId) {
|
|
|
- try {
|
|
|
- if (!embeddingProvider.isAvailable()) {
|
|
|
- return;
|
|
|
- }
|
|
|
- int dimensions = embeddingProvider.dimensions();
|
|
|
- if (dimensions <= 0) {
|
|
|
- return;
|
|
|
+ synchronized (rebuildLock) {
|
|
|
+ try {
|
|
|
+ if (!embeddingProvider.isAvailable() || !vectorStore.isAvailable()) {
|
|
|
+ return;
|
|
|
+ }
|
|
|
+ int dimensions = embeddingProvider.dimensions();
|
|
|
+ if (dimensions <= 0) {
|
|
|
+ return;
|
|
|
+ }
|
|
|
+ removeDoc(vectorTableName(embeddingProvider.tableTag(), dimensions), docId);
|
|
|
+ } catch (Exception e) {
|
|
|
+ log.error("删除模板向量失败(已降级): docId={}, error={}", docId, e.getMessage());
|
|
|
}
|
|
|
- removeDoc(vectorTableName(embeddingProvider.tableTag(), dimensions), docId);
|
|
|
- } catch (Exception e) {
|
|
|
- log.error("删除模板向量失败(已降级): docId={}, error={}", docId, e.getMessage());
|
|
|
}
|
|
|
}
|
|
|
|
|
|
private void removeDoc(String vectorTable, String docId) {
|
|
|
- if (!vectorTableExists(vectorTable)) {
|
|
|
+ if (!vectorStore.collectionExists(vectorTable)) {
|
|
|
return;
|
|
|
}
|
|
|
try {
|
|
|
- int deleted = aiCleanVectorMapper.deleteVectorDoc(vectorTable, docId);
|
|
|
+ int deleted = vectorStore.delete(vectorTable, docId);
|
|
|
if (deleted > 0) {
|
|
|
- log.info("已删除模板向量: table={}, docId={}, rows={}", vectorTable, docId, deleted);
|
|
|
+ vectorStore.flush(vectorTable);
|
|
|
+ log.info("已删除模板向量: collection={}, docId={}, rows={}", vectorTable, docId, deleted);
|
|
|
}
|
|
|
} catch (Exception e) {
|
|
|
- log.error("删除模板向量失败(已降级): table={}, docId={}, error={}",
|
|
|
+ log.error("删除模板向量失败(已降级): collection={}, docId={}, error={}",
|
|
|
vectorTable, docId, e.getMessage());
|
|
|
}
|
|
|
}
|
|
|
@@ -648,9 +667,14 @@ public class AiCleanTemplateVectorIndex {
|
|
|
// ==================== 文档构建(包内可见纯函数:离线单测直接断言) ====================
|
|
|
|
|
|
/**
|
|
|
- * 待写入向量表的一篇文档。
|
|
|
+ * 待写入 zvec 的一篇文档。
|
|
|
+ *
|
|
|
+ * @param kind 文档类型({@link #KIND_TABLE} / {@link #KIND_AI}),作为 zvec 标量字段参与过滤
|
|
|
+ * @param docId 主键({@code t:*} / {@code a:*})
|
|
|
+ * @param content 用于嵌入的原文
|
|
|
+ * @param payloadJson 召回后反解模板信息的业务载荷
|
|
|
*/
|
|
|
- record VectorDoc(String docId, String content, String payloadJson) {
|
|
|
+ record VectorDoc(String kind, String docId, String content, String payloadJson) {
|
|
|
}
|
|
|
|
|
|
/**
|
|
|
@@ -692,7 +716,7 @@ public class AiCleanTemplateVectorIndex {
|
|
|
payload.put("headers", headers);
|
|
|
payload.put("fields", toPayloadFields(briefs));
|
|
|
payload.put("category", table.getClassify());
|
|
|
- return new VectorDoc(DOC_ID_TABLE_PREFIX + table.getId(),
|
|
|
+ return new VectorDoc(KIND_TABLE, DOC_ID_TABLE_PREFIX + table.getId(),
|
|
|
buildContent("既有模板", table.getTableNameEn(), table.getTableNameCn(), headers, briefs),
|
|
|
Json.toStr(payload));
|
|
|
}
|
|
|
@@ -723,7 +747,7 @@ public class AiCleanTemplateVectorIndex {
|
|
|
payload.put("headers", headers);
|
|
|
payload.put("fields", toPayloadFields(briefs));
|
|
|
payload.put("category", template.getCategory());
|
|
|
- return new VectorDoc(DOC_ID_AI_PREFIX + template.getId(),
|
|
|
+ return new VectorDoc(KIND_AI, DOC_ID_AI_PREFIX + template.getId(),
|
|
|
buildContent("AI 模板", template.getTableNameEn(), template.getTableNameCn(), headers, briefs),
|
|
|
Json.toStr(payload));
|
|
|
}
|
|
|
@@ -852,8 +876,8 @@ public class AiCleanTemplateVectorIndex {
|
|
|
try {
|
|
|
double[] vector = embeddingProvider.embed(content);
|
|
|
if (vector == null || vector.length != dimensions) {
|
|
|
- // 维度不符说明模型配置与实际输出对不上:这一行写进去会让整表向量检索崩掉
|
|
|
- // (pgvector 的 vector(n) 列强校验维度),所以宁可跳过并告警
|
|
|
+ // 维度不符说明模型配置与实际输出对不上:zvec collection 的向量字段维度固定,
|
|
|
+ // 写错维度会让整批写入失败,所以宁可跳过并告警
|
|
|
log.info("嵌入向量维度不一致,跳过该模板文档(期望 {},实际 {}): model={}",
|
|
|
dimensions, vector == null ? 0 : vector.length, embeddingProvider.modelName());
|
|
|
return null;
|
|
|
@@ -875,8 +899,8 @@ public class AiCleanTemplateVectorIndex {
|
|
|
if (vector == null) {
|
|
|
return false;
|
|
|
}
|
|
|
- aiCleanVectorMapper.upsertVectorDoc(vectorTable, doc.docId(), doc.content(),
|
|
|
- doc.payloadJson(), toVectorLiteral(vector));
|
|
|
+ vectorStore.upsert(vectorTable, doc.docId(), doc.kind(), doc.content(),
|
|
|
+ doc.payloadJson(), toFloatArray(vector));
|
|
|
return true;
|
|
|
} catch (Exception e) {
|
|
|
log.error("写入模板向量失败,跳过该文档: docId={}, error={}", doc.docId(), e.getMessage());
|
|
|
@@ -884,53 +908,27 @@ public class AiCleanTemplateVectorIndex {
|
|
|
}
|
|
|
}
|
|
|
|
|
|
- private void ensureVectorTable(String vectorTable, int dimensions) {
|
|
|
- if (ensuredVectorTables.contains(vectorTable)) {
|
|
|
- return;
|
|
|
- }
|
|
|
- aiCleanVectorMapper.createVectorTableIfNotExists(vectorTable, dimensions);
|
|
|
- ensuredVectorTables.add(vectorTable);
|
|
|
- }
|
|
|
-
|
|
|
- private boolean vectorTableExists(String vectorTable) {
|
|
|
- if (ensuredVectorTables.contains(vectorTable)) {
|
|
|
- return true;
|
|
|
- }
|
|
|
- try {
|
|
|
- if (aiCleanVectorMapper.tableExists(vectorTable) > 0) {
|
|
|
- ensuredVectorTables.add(vectorTable);
|
|
|
- return true;
|
|
|
- }
|
|
|
- } catch (Exception e) {
|
|
|
- log.debug("探测模板向量表是否存在失败: table={}, error={}", vectorTable, e.getMessage());
|
|
|
- }
|
|
|
- return false;
|
|
|
- }
|
|
|
-
|
|
|
/**
|
|
|
- * 向量表名:rag_tpl{tag}_d{dims}。
|
|
|
+ * collection 名:rag_tpl{tag}_d{dims}。
|
|
|
*
|
|
|
- * <p>维度进表名:换嵌入模型且维度变化时自然落到新表,不会出现「旧表 vector(1024) 塞 1536 维」的写失败。
|
|
|
- * 模型名也进表名(如 {@code rag_tpl_bge_m3_d1024}):换模型后新旧向量物理隔离,
|
|
|
- * 不会把另一套向量空间的结果当成当前索引继续检索。
|
|
|
- * 旧表按设计留待人工清理(见设计文档 §7)。
|
|
|
+ * <p>维度进 collection 名:换嵌入模型且维度变化时自然落到新目录,不会出现「旧 collection
|
|
|
+ * 按 1024 维建、却塞 1536 维向量」的写失败。模型名也进名字(如 {@code rag_tpl_bge_m3_d1024}):
|
|
|
+ * 换模型后新旧向量物理隔离,不会把另一套向量空间的结果当成当前索引继续检索。
|
|
|
+ * 旧目录按设计留待人工清理(见设计文档 §7)。
|
|
|
*/
|
|
|
static String vectorTableName(String tag, int dimensions) {
|
|
|
- return VECTOR_TABLE_PREFIX + (tag == null ? "" : tag) + "_d" + dimensions;
|
|
|
+ return VECTOR_COLLECTION_PREFIX + (tag == null ? "" : tag) + "_d" + dimensions;
|
|
|
}
|
|
|
|
|
|
/**
|
|
|
- * double[] → pgvector 字面量(如 [0.1,0.2,...])。
|
|
|
+ * double[] → float[]:zvec 的写入/查询向量统一为 FP32 数组。
|
|
|
*/
|
|
|
- private static String toVectorLiteral(double[] vector) {
|
|
|
- StringBuilder sb = new StringBuilder(vector.length * 10).append('[');
|
|
|
+ private static float[] toFloatArray(double[] vector) {
|
|
|
+ float[] out = new float[vector.length];
|
|
|
for (int i = 0; i < vector.length; i++) {
|
|
|
- if (i > 0) {
|
|
|
- sb.append(',');
|
|
|
- }
|
|
|
- sb.append(vector[i]);
|
|
|
+ out[i] = (float) vector[i];
|
|
|
}
|
|
|
- return sb.append(']').toString();
|
|
|
+ return out;
|
|
|
}
|
|
|
|
|
|
/**
|