LLM大语言模型(六):RAG模式下基于PostgreSQL pgvector插件实现vector向量相似性检索

目录

HightLight

使用PostgreSQL来存储和检索vector,在数据规模非庞大的情况下,简单高效。

可以和在线业务共用一套DB,减少其他组件的引入,降低复杂度,在业务初期可以极大的提升效率。

Mac上安装PostgreSQL

强烈建议使用Postgres.app模式安装

下载最新版(我下载的是16,已包含pgvector插件)
https://postgresapp.com/downloads.html

图形界面安装,很简单

一定要"Initialize"

bash 复制代码
Installing Postgres.app
Download   ➜   Move to Applications folder   ➜   Double Click

If you don't move Postgres.app to the Applications folder, some features may not work (more info)

Click "Initialize" to create a new server

Configure your $PATH to use the included command line tools (optional):

sudo mkdir -p /etc/paths.d &&
echo /Applications/Postgres.app/Contents/Versions/latest/bin | sudo tee /etc/paths.d/postgresapp

DBever图形界面管理端

创建DB

创建mydb

使用向量检索

SQL 复制代码
# 在mydb里启用pgvector插件
CREATE EXTENSION vector;

# 创建一张表items,其中的embedding字段是vector类型
CREATE TABLE items (id bigserial PRIMARY KEY, embedding vector(3));

# 添加数据
INSERT INTO items (embedding) VALUES ('[1,2,3]'), ('[4,5,6]');

# 相似性检索
SELECT * FROM items ORDER BY embedding <-> '[3,1,2]' LIMIT 5;

vector相似度计算

符号 相似度计算
<-> L2距离
<=> cosine距离
<#> inner product点积距离

近似近邻索引

默认情况下pgvector提供的是精确近邻检索,也即全量计算找近邻,召回精准,但计算性能差。

pgvector还提供了两种近似近邻索引:

  1. HNSW - added in 0.5.0
  2. IVFFlat

HNSW近似近邻索引示例

sql 复制代码
# Add an index for each distance function you want to use.

# 创建L2 distance的hnsw近似近邻索引

CREATE INDEX ON items USING hnsw (embedding vector_l2_ops);

# 创建Inner product distance的hnsw近似近邻索引

CREATE INDEX ON items USING hnsw (embedding vector_ip_ops);

# 创建Cosine distance的hnsw近似近邻索引

CREATE INDEX ON items USING hnsw (embedding vector_cosine_ops);

2000维以内都可以索引。

Vectors with up to 2,000 dimensions can be indexed.

具体使用哪种近似近邻索引,根据具体业务来测试。

相关推荐
csdn_aspnet7 小时前
如何用 C# 和 Gemma 3 在本地构建一个真正能完成工作的 AI 代理的
人工智能·ai·c#·gemma
啊哈哈哈哈哈啊哈哈7 小时前
边缘计算与轮廓检测
人工智能·opencv·计算机视觉
cskywit7 小时前
从DFL到无NMS推理:一文拆解YOLO26背后的工程取舍与数学原理
人工智能·机器学习
PPHT-H8 小时前
【人工智能笔记】第四十四节:OpenClaw封神工具 openclaw-free-openai-proxy 免费AI模型批量调用,零token费+稳到不翻车!
人工智能·深度学习·openclaw·免费openai·ai服务代理
yiyu07168 小时前
3分钟搞懂深度学习AI:实操篇:RNN
人工智能·深度学习
uzong8 小时前
CoPaw是什么?-- 2026年开源的国产个人AI助手
人工智能·后端
海盗儿8 小时前
TensorRT-LLM 框架与源码分析
人工智能
无心水8 小时前
【任务调度:框架】11、分布式任务调度进阶:高可用、幂等性、性能优化三板斧
人工智能·分布式·后端·性能优化·架构·2025博客之星·分布式调度框架
gujunge8 小时前
Spring with AI (2): 评估答案——UnitTest引入
ai·大模型·llm·openai·qwen·rag·spring ai·deepseek
码森林8 小时前
小龙虾居然比你更健忘?OpenClaw 记忆系统指南,让它永远记住你
人工智能·ai编程·全栈