|
| 1 | +import type { NextApiRequest, NextApiResponse } from 'next'; |
| 2 | +import { jsonRes } from '@fastgpt/service/common/response'; |
| 3 | +import { connectToDatabase } from '@/service/mongo'; |
| 4 | +import { authCert } from '@fastgpt/service/support/permission/auth/common'; |
| 5 | +import { PgClient } from '@fastgpt/service/common/vectorStore/pg'; |
| 6 | +import { DatasetVectorTableName } from '@fastgpt/service/common/vectorStore/constants'; |
| 7 | + |
| 8 | +export default async function handler(req: NextApiRequest, res: NextApiResponse) { |
| 9 | + try { |
| 10 | + await connectToDatabase(); |
| 11 | + await authCert({ req, authRoot: true }); |
| 12 | + |
| 13 | + // pg 新建字段:halfvector |
| 14 | + const columnExists = await PgClient.query(` |
| 15 | + SELECT column_name |
| 16 | + FROM information_schema.columns |
| 17 | + WHERE table_name='${DatasetVectorTableName}' AND column_name='halfvector'; |
| 18 | + `); |
| 19 | + |
| 20 | + if (columnExists.rows.length === 0) { |
| 21 | + await PgClient.query(` |
| 22 | + BEGIN; |
| 23 | + ALTER TABLE ${DatasetVectorTableName} ADD COLUMN halfvector halfvec(1536); |
| 24 | + COMMIT; |
| 25 | + `); |
| 26 | + console.log('halfvector column added'); |
| 27 | + } |
| 28 | + |
| 29 | + let rowsUpdated; |
| 30 | + do { |
| 31 | + rowsUpdated = await PgClient.query(` |
| 32 | + WITH updated AS ( |
| 33 | + UPDATE ${DatasetVectorTableName} |
| 34 | + SET halfvector = vector::halfvec(1536) |
| 35 | + WHERE id IN ( |
| 36 | + SELECT id |
| 37 | + FROM ${DatasetVectorTableName} |
| 38 | + WHERE halfvector IS NULL |
| 39 | + LIMIT 1000 |
| 40 | + ) |
| 41 | + RETURNING 1 |
| 42 | + ) |
| 43 | + SELECT count(*) FROM updated; |
| 44 | + `); |
| 45 | + console.log('rowsUpdated:', rowsUpdated.rows[0].count); |
| 46 | + } while (rowsUpdated.rows[0].count > 0); |
| 47 | + |
| 48 | + // 设置halfvector字段为非空 |
| 49 | + await PgClient.query( |
| 50 | + `BEGIN; |
| 51 | + ALTER TABLE ${DatasetVectorTableName} ALTER COLUMN halfvector SET NOT NULL; |
| 52 | + DROP INDEX IF EXISTS vector_index; |
| 53 | + ALTER TABLE ${DatasetVectorTableName} DROP COLUMN IF EXISTS vector; |
| 54 | + COMMIT; |
| 55 | + ` |
| 56 | + ); |
| 57 | + |
| 58 | + // 后台释放空间,避免使用 VACUUM FULL 导致锁表。 |
| 59 | + await PgClient.query(`VACUUM ${DatasetVectorTableName};`); |
| 60 | + |
| 61 | + jsonRes(res, { |
| 62 | + message: 'success' |
| 63 | + }); |
| 64 | + } catch (error) { |
| 65 | + console.log(error); |
| 66 | + |
| 67 | + jsonRes(res, { |
| 68 | + code: 500, |
| 69 | + error |
| 70 | + }); |
| 71 | + } |
| 72 | +} |
0 commit comments