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.

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

相关推荐
海蓝可知天湛9 小时前
Agent&IELTS雅思口语专属语料库
人工智能·github·rag·ielts·skills
随身数智备忘录9 小时前
什么是设备管理体系?设备管理体系包含哪些核心模块?
网络·数据库·人工智能
OpenBayes贝式计算9 小时前
涵盖 OCR 与多轮对话:1.3B 端侧多模态模型 MiniCPM-V-4.6 正式发布;百万级智能体数据集 AgentTrove 开源!包含代码修复及数学求解
人工智能
1892280486110 小时前
NY352固态MT29F32T08GWLBHD6-24QJ:B
大数据·服务器·人工智能·科技·缓存
南屹川10 小时前
【数据库】PostgreSQL实战:从基础到高级特性
人工智能
zhangxingchao10 小时前
多 Agent 架构到底怎么选?从 Claude Agent Teams、Cognition/Devin 到工程落地原则
前端·人工智能·后端
不开大的凯207710 小时前
麦当秀AiPPT战略转向:从SaaS订阅迈向Token经济,AI办公定价模式迎来新探索
大数据·人工智能
Mr数据杨10 小时前
【CanMV K210】显示交互 LCD1602 I2C 通信与滚动文本显示
人工智能·交互·硬件开发·canmv k210
IT_陈寒10 小时前
SpringBoot那个自动配置的坑,害我排查到凌晨三点
前端·人工智能·后端
常威正在打来福10 小时前
不想让你的网页长得像「AI 做的」?试试这个
人工智能·aigc·ai编程