#!/usr/bin/env node 'use strict'; // 给旧 bridge 的 products.kb_docs 补 Hybrid RAG 所需字段并回填全文索引。 // 幂等;不改动已有数据,只新增列/索引。 const { Client } = require('../bridge/node_modules/pg'); const PG_URL = process.env.KB_OLD_PG_URL || 'postgres://postgres:postgres@127.0.0.1:5432/products'; async function main() { const client = new Client({ connectionString: PG_URL }); await client.connect(); await client.query('ALTER TABLE kb_docs ADD COLUMN IF NOT EXISTS parent_id INTEGER'); await client.query("ALTER TABLE kb_docs ADD COLUMN IF NOT EXISTS chunk_type TEXT DEFAULT 'parent'"); await client.query('ALTER TABLE kb_docs ADD COLUMN IF NOT EXISTS keywords_text TEXT'); await client.query('ALTER TABLE kb_docs ADD COLUMN IF NOT EXISTS text_tsv tsvector'); await client.query(` UPDATE kb_docs SET text_tsv = to_tsvector('english', coalesce(question, '') || ' ' || coalesce(answer, '') || ' ' || coalesce(array_to_string(keywords, ' '), '') || ' ' || coalesce(title, '') || ' ' || coalesce(section, '')) WHERE text_tsv IS NULL `); await client.query('CREATE INDEX IF NOT EXISTS kb_docs_tsv_idx ON kb_docs USING GIN (text_tsv)'); await client.query('CREATE INDEX IF NOT EXISTS kb_docs_parent_idx ON kb_docs (parent_id) WHERE parent_id IS NOT NULL'); const r = await client.query("SELECT COUNT(*)::int AS total, COUNT(*) FILTER (WHERE text_tsv IS NOT NULL)::int AS indexed FROM kb_docs"); console.log(JSON.stringify(r.rows[0])); await client.end(); } main().catch((err) => { console.error('[upgrade-kb-schema]', err.message); process.exit(1); });