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.

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

相关推荐
青稞社区.13 小时前
直播预告!面向几何与运动理解的流式前馈 3D/4D 重建
人工智能·3d
HIT_Weston13 小时前
85、【Agent】【OpenCode】bash 工具提示词(HEREDOC)
人工智能·agent·opencode
AI技术控13 小时前
Transformer 的 Encoder 和 Decoder 模块介绍:从结构原理到大模型应用实践
人工智能·python·深度学习·自然语言处理·transformer
Codebee13 小时前
日抛型软件的双链路设计——从"日抛"到"认知进化"的范式革命
人工智能
KaMeidebaby13 小时前
卡梅德生物技术快报|单克隆抗体人源化 PEG 修饰质控方法体系构建与验证
服务器·前端·数据库·人工智能·算法·百度·新浪微博
LaughingZhu13 小时前
Product Hunt 每日热榜 | 2026-05-16
人工智能·经验分享·深度学习·神经网络·产品运营
wuxinyan12313 小时前
工业级大模型学习之路015:RAG零基础入门教程(第十一篇):系统重构与代码规范化
人工智能·python·学习·重构·rag
灵机一物13 小时前
灵机一物AI原生电商小程序、PC端(已上线)-【技术深度解析】Bun 6 天 AI 重写 96 万行代码:从 Zig 迁移 Rust 全流程与行业影响
开发语言·人工智能·rust
wuxinyan12313 小时前
工业级大模型学习之路014:RAG零基础入门教程(第十篇):系统性能与资源优化
人工智能·学习·rag