12345678910111213141516171819202122232425262728293031323334353637383940 |
- // routes.js
- const express = require('express');
- const router = express.Router();
- // 数据库连接配置
- const psqlDB = require("../../../psql.service");
- // 计算余弦相似度的 SQL 查询
- const cosineSimilarityQuery = `
- SELECT "objectId","story","pageContent",(1 - (vector_array::vector <=> $1::vector)) AS similarity
- FROM (
- SELECT *,
- (SELECT array_agg(value::float)
- FROM jsonb_array_elements(vector512) AS value) AS vector_array
- FROM "Document"
- WHERE ($2 IS NULL OR story = $2)
- ) AS subquery
- ORDER BY similarity
- LIMIT 20;
- `;
- // POST 路由处理
- router.post('/retrive', async (req, res) => {
- const { search, vector512, story } = req.body;
- if (!Array.isArray(vector512)) {
- return res.status(400).json({ error: 'Invalid input' });
- }
- try {
- const result = await psqlDB.any(cosineSimilarityQuery, [vector512, story]);
- res.json(result);
- } catch (error) {
- console.error('Database query error:', error);
- console.error(error)
- res.status(500).json({ error: 'Database query error' });
- }
- });
- module.exports = router;
|