routes.js 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. // routes.js
  2. const express = require('express');
  3. const router = express.Router();
  4. // 数据库连接配置
  5. const psqlDB = require("../../../psql.service");
  6. // 计算余弦相似度的 SQL 查询
  7. const cosineSimilarityQuery = `
  8. SELECT "objectId","story","pageContent",(1 - (vector_array::vector <=> $1::vector)) AS similarity
  9. FROM (
  10. SELECT *,
  11. (SELECT array_agg(value::float)
  12. FROM jsonb_array_elements(vector512) AS value) AS vector_array
  13. FROM "Document"
  14. WHERE ($2 IS NULL OR story = $2)
  15. ) AS subquery
  16. ORDER BY similarity DESC
  17. LIMIT 20;
  18. `;
  19. // POST 路由处理
  20. router.post('/retrive', async (req, res) => {
  21. const { search, vector512, story } = req.body;
  22. if (!Array.isArray(vector512)) {
  23. return res.status(400).json({ error: 'Invalid input' });
  24. }
  25. try {
  26. const result = await psqlDB.any(cosineSimilarityQuery, [vector512, story]);
  27. res.json(result);
  28. } catch (error) {
  29. console.error('Database query error:', error);
  30. console.error(error)
  31. res.status(500).json({ error: 'Database query error' });
  32. }
  33. });
  34. module.exports = router;