PostgreSQL 扩展生态全景解析(第三期):pgvector —— 当关系型数据库“理解”语义
Clyde Jin
04-24
DBA
65

PostgreSQL 扩展生态全景解析(第三期):pgvector —— 当关系型数据库“理解”语义

引言:从“匹配关键词”到“理解含义”

继续我们的扩展之旅。如果说第二期的 PostGIS 让数据库“看懂”了地图,解决了“我在哪里”的几何空间问题,那么本期的 pgvector 则要回答一个更抽象的问题:“它像什么?”

想象一个电商场景。用户输入“送长辈的礼盒”。普通的关键词搜索如果只匹配商品标题,会漏掉那些标题不含“礼盒”二字却符合“挑选给长辈”这一意图的商品。而一个能“理解”语义意图的系统,则能穿透字面的屏障,在更深处定位到真正的需求。

pgvector 正是在这样的背景下应运而生的。它把文本、图像等信息转化成高维向量(Embedding),让数据库不仅能存和查,还能通过向量运算进行语义相似性搜索

而 pgvector 真正的变革力量在于——它让这一切在标准 SQL 内就以“原生”方式实现了:

CREATE EXTENSION vector;

CREATE TABLE products (
    id bigserial PRIMARY KEY,
    name text,
    description text,
    embedding vector(1536)      -- AI 生成的 1536 维向量
);

CREATE INDEX ON products USING hnsw (embedding vector_cosine_ops);

-- 寻找语义最相似的商品
SELECT * FROM products
ORDER BY embedding <=> '[0.012, -0.003, ...]'  -- 查询的向量表示
LIMIT 10;

没有引入新的技术栈,没有额外的数据同步管道,就在 PostgreSQL 内部,语义搜索的能力生长了出来。pgvector 是如何做到让关系型数据库“理解”向量的?这正是本期要深入探究的核心。

一、核心概念:向量是什么?pgvector 如何定义“相似”?

1.1 向量类型:不止一种“数组”

pgvector 提供了多种向量数据类型,以适应不同精度和存储效率的需求。

类型 元素 单元素大小 最大维度 存储公式(近似) 适用场景
vector(n) float32 4 字节 2,000(索引)/ 16,000(存储) 4×n + 8 字节 默认类型,平衡精度与性能
halfvec(n) float16 2 字节 4,000 / 16,000 2×n + 8 字节 超大规模数据集,节省 50% 存储
bit(n) 二进制位 1/8 字节 64,000 n/8 + 8 字节 哈希签名、二进制向量
sparsevec(n) 稀疏向量 索引+值 ~1,000 non-zero 8×n_nz + 16 字节 高维稀疏嵌入(如词袋模型)

每种类型都有固定的维度上限,创建时需明确指定。选择何种类型需要权衡:vector 精度最高,halfvec 节省存储但精度减半,sparsevec 则专为绝大多数元素为零的稀疏向量设计。

存储机制的巧妙之处:当向量长度适中时,PostgreSQL 会将向量数据直接内联存储在同一条数据行的页面上,避免额外的 TOAST 读取 I/O,让向量和数据保持在同一物理页。对于超长向量,PostgreSQL 会自动压缩或将其移至 TOAST 表,以空间换时间。

⚠️ 小提示:HNSW 索引对 vector 类型有 2000 维的上限,4096 维的 BGE 模型需改用 halfvecsparsevec 自身不支持 HNSW 索引,通常需要配合 IVFFlat 或精确搜索。

1.2 三种核心距离:选对度量,事半功倍

pgvector 提供了三种核心的距离运算符,对应不同的业务含义,决定了检索结果的“好坏”。

运算符 距离类型 语义 取值范围 适用场景
<-> L2(欧几里得)距离 空间中两点的直线距离,对长度敏感 [0, ∞) 物理位置、传感器数据
<=> 余弦距离 只关心方向(夹角余弦),不关心长度 [0, 2] 文本语义、图像内容、推荐系统
<#> 内积(取负) 角度与长度都敏感 (-∞, ∞) 未归一化的向量、最大内积搜索(MIPS)

选型原则:OpenAI/Cohere 主流嵌入模型已默认归一化,此时余弦距离 <=> 是语义搜索的标准选择;L2 <-> 适合保留长度信息的场景还是空间坐标;内积 <#> 则在推荐系统中常用,因为用户向量和物品向量的模长可以编码交互频率或流行度。若不确定,可对几条已知的正负样本分别排序,观察哪种度量将正确答案前置。

⚠️ 最常见的坑——索引失效:pgvector 索引在创建时绑定了一个具体的操作符类(operator class),用 vector_cosine_ops 建索引后查询必须用 <=>,否则索引失效,退化为全表扫描。有团队因此遭遇了 600 倍的性能暴跌。排查技巧:先看 EXPLAIN ANALYZE 是否走 Index Scan,再看操作符与索引类是否匹配。

二、索引决战:HNSW vs IVFFlat

在百万甚至千万级的向量数据上执行精确最近邻(KNN)搜索会涉及大量计算,所以 pgvector 使用近似最近邻(ANN)索引来加速检索。HNSW 和 IVFFlat 是两种主流选择,但它们的设计哲学和适用场景完全不同。

2.1 IVFFlat:朴素但高效的万金油

IVFFlat 通过 K-Means 将向量空间分割成若干“聚类桶”。查询时,它只搜索距离查询向量最近的若干“桶”,而非全量扫描。

核心参数lists 表示聚类的桶数量,推荐公式约为 行数 / 1000。查询参数 probes 表示查询时扫描多少个桶,典型取值 probes = sqrt(lists)

核心特征:IVFFlat 像“预分类”,建索引很快(只需要一次聚类),内存占用低,但索引必须在导入数据后构建,且对动态更新(频繁 INSERT)适应较差。如果你有资源受限的环境或大规模增量写入,IVFFlat 是优选的轻量级方案。

2.2 HNSW:图结构的“高速导航”

HNSW(Hierarchical Navigable Small World)是 pgvector 默认推荐的索引类型,性能出色且对动态数据更稳健。它通过构建多层级图结构实现高效的近似最近邻搜索:顶层稀疏(像“地图缩放后的概览”),底层密集,每层节点相互连接,形成可导航的“小世界”网络。

核心特征:复杂度 O(log N),查找速度极快,召回率稳定,但索引构建慢(比 IVFFlat 慢很多)、内存占用高。因此 HNSW 适合读多写少、对查询延迟敏感的场景。

关键参数调优

  • m:每层最大连接数,默认 16。较高 m 适合高维数据和高精度要求,16-48 是常用起始范围。
  • ef_construction:索引创建时的动态池大小,默认 64。越大索引质量越高,但构建也越耗时。
  • ef_search:查询时的候选池大小,默认 40。增大可提升召回率。
💡 调优建议:检查 ef_search = ef_construction 时的精度,若低于 0.9,仍有提升空间。

三、性能优化:让你的 pgvector 跑得更快

3.1 “Overfiltering” 陷阱与 pgvector 0.8 的突破

在向量搜索加上业务过滤(如 WHERE 条件)时,老版本 pgvector 会先执行向量索引取出“最近”的邻居,再进行过滤,导致过过滤(Overfiltering)。如果过滤条件苛刻,返回的结果可能为空。

pgvector 0.8.0 引入的迭代索引扫描(iterative_scan) 通过全局视角逐步扩大搜索范围,让过滤条件提前参与向量扫描,在精度和性能上实现了更好的平衡。

3.2 边缘生态:pgvectorscale 将 Postgres 推向更大规模

随着业务向量规模从千万级迈向亿级,原生 pgvector 在高并发和内存上会遇到瓶颈。pgvectorscale 作为 pgvector 的补充扩展,带来了两项关键技术:

  • StreamingDiskANN:将索引的大部分数据存储在磁盘上而非内存中,使 PostgreSQL 能够以更低成本支持十亿级向量检索。
  • 统计二进制量化(SBQ):压缩向量表示,降低存储成本并加速索引遍历。

3.3 性能检查清单

  1. 查看执行计划EXPLAIN ANALYZE 是否显示 Index Scan using hnsw,若退化为 Seq Scan 说明查询优化器放弃使用索引。
  2. 检查操作符与操作符类的绑定:索引类和查询操作符必须严格对应(vector_cosine_ops<=>)。
  3. 存储策略调优:中小规模向量内联存储(默认行为)即可。刻意使用 ALTER TABLE … SET STORAGE PLAIN 往往没必要,在真正出性能瓶颈时再去考虑。

四、全文搜索(BM25)+ 向量检索 = “混合搜索”

向量搜索擅长泛化语义匹配,但有时无法精准匹配特定实体词(比如专有名词“mysql_fdw 扩展”)。而传统的全文搜索(BM25)擅长精确关键词匹配,却难以理解同义词转换。混合搜索正是将二者融合。

实现策略大致是:先用向量搜索召回语义相关的候选集(如前 100 条),再用 BM25 进行精确过滤或加权融合排序。BM25 部分既可用 PostgreSQL 自带的 GIN 全文索引,也可借助新生态插件 pg_textsearch。加权排序公式(如 0.7 <em> vector_score + 0.3 </em> text_score)可按业务实际微调。

在技术问答、电商产品搜索等场景中,混合搜索通常能在纯语义和纯关键词的两难中找到最佳平衡点,有效提升召回率和排序效果。

五、向量 + 地理:PostGIS 与 pgvector 的自然融合

你可能会问:第一期的全文搜索、第二期的地理空间和第三期的向量搜索,只是在同一个数据库中共存,还是能真正协同工作?答案是:它们不仅能共存,还能在 1+1 > 2 的组合中产生全新的能力。

想象一个新零售智能选址系统:用户用自然语言输入“沿中关村大街 500 米内、类似‘网红打卡氛围’的潮流饮品店”。数据库需要在空间上计算“500 米缓冲区”,同时在语义上匹配“网红打卡氛围”的高维向量,二者缺一不可。

使用 PostgreSQL 的组合方案:

SELECT store_id, name, geom, embedding
FROM stores
WHERE ST_DWithin(geom, ST_GeomFromText('POINT(116.31 39.98)', 4326), 500.0)
ORDER BY embedding <=> query_embedding
LIMIT 10;

PostgreSQL 的优化器能够同时处理 GiST 空间索引和 HNSW 向量索引,在空间上筛选出的候选集数量大幅降低后,再进行向量距离计算,性能远超两套系统联动。在全球 FOSS4G 2025 大会上,已经出现了「自然语言 + NL2SQL + PostGIS + pgvector」语义空间搜索的演示项目,它能够理解“附近最高建筑”这样的抽象表达,自动转化为坐标查询与向量检索,并推荐最优位置。这让我们隐约看见了“AI 原生时空数据库”的未来雏形。

六、横向对比:pgvector vs 专用向量数据库

尽管 pgvector 功能强大,但它并非无所不能的“银弹”。业界常用的专用向量数据库包括 Pinecone(全托管,开箱即用)、Qdrant(开源,Rust 编写)和 Milvus(云原生,分布式架构)。

  • 集成复杂度:pgvector 直接作为插件在现有 PostgreSQL 实例中启用,意味着只需管理一个数据库、一套权限、一套备份;而引入专用向量数据库意味着第二套系统,需要自己维护数据同步和两套系统的事务一致性。
  • 扩展规模:专用向量数据库通常为亿级甚至十亿级向量设计,天生支持水平分片和多副本;pgvector + pgvectorscale 处于上升通道,但生产环境超过几百万向量时仍建议进行压力测试。
  • 高级特性:专用数据库有更丰富的量化方法(把向量压缩存储,减少内存需求)和分布式部署策略;pgvector 和 pgvectorscale 的模型量化能力相对基础。
  • 去重与 MVCC:pgvector 索引指向具体元组,与 MVCC(多版本并发控制)体系深度整合,写入时不会出现索引膨胀问题。

选型建议:对于中小型团队、不想引入额外基础设施的“保守”路径或对数据一致性要求高的业务,pgvector 是非常务实的选择。当向量规模超过千万且查询 QPS 极高、容错需求强时,可评估迁移到专用向量数据库的成本。

七、实战:快速搭建一个 RAG 应用

RAG(检索增强生成)是目前大语言模型落地的核心范式:先将文档切成块,调用嵌入模型生成向量,存入 pgvector;当用户提问时,通过向量相似度检索最相关的文本块,将查询结果作为上下文提供给大模型以生成最终回答。

生产级 RAG 的最小实现步骤:

CREATE EXTENSION vector;

CREATE TABLE knowledge_base (
    id SERIAL PRIMARY KEY,
    content TEXT,
    embedding vector(1536),
    metadata JSONB
);

-- 创建 HNSW 索引
CREATE INDEX ON knowledge_base USING hnsw (embedding vector_cosine_ops);

-- 查询相似上下文
WITH context AS (
    SELECT content, metadata
    FROM knowledge_base
    ORDER BY embedding <=> $1::vector(1536)
    LIMIT 5
)
SELECT fn_generate_answer('用户提问', context);  -- 调用 LLM

实践中还需考虑长文档智能分块、元数据预过滤(如按用户 ID 分租户)、定时同步嵌入流水线以及使用 pgvector 8.0 提供的 iterative_scan 解决过滤查询的过过滤问题等细节。将三者合理组合,即可构建一个稳定、高性能的 AI 知识库系统。

八、未来展望:从 AI 查询到 AI 原生数据库

HNSW 算法的持续演进

HNSW 加速向量检索的能力基本经过了广泛的生产验证,但新版本 pgvector 也在探索不同的内存/磁盘平衡(如 StreamingDiskANN)和 label filtering 的集成,简化带条件的向量搜索代价。

数据库层面正在“原生吸收”向量能力

PostgreSQL 17 已原生支持向量,将 vector 类型内置,并新增了 IVFFlat 索引的并行构建能力和更高的维度上限,已在 AWS、阿里云等云平台中逐步默认启用。pgvector 更多扮演先行者和孵化器角色。

向量检索正成为标准上云能力

pgvector 已被集成到主流云数据库托管服务(如 Amazon Aurora、Google AlloyDB、阿里云 PolarDB、Supabase、Neon)中,成为标准“开箱即用”的功能。Azure Database for PostgreSQL 和 AWS Bedrock 则提供了与各项 AI 服务的无缝联动。

写在最后

从 PostGIS 到 pgvector,我们看到了 PostgreSQL 扩展生态的两个奇迹。一个让数据库“看懂空间”,一个让数据库“理解语义”。它们所依赖的根本机制是一致的——自定义数据类型、高度抽象的索引接口、以及 Postgres 对整个生态完全开放的设计哲学。

本期我们拆解了 pgvector 的核心向量类型、HNSW 和 IVFFlat 的索引争锋、全文 BM25 + 向量的混合检索、与 PostGIS 的地空协同以及 RAG 落地中需要注意的陷阱与优化。三条完整的技术线——GIS、全文搜索和向量检索——今天已经可以在同一个 PostgreSQL 实例中稳定、高效地组合工作。

如果说 Postgres 是一个操作系统,那么 PostGIS 就是它的 GIS 子系统,而 pgvector 则是它的 AI 加速卡。而这三者能够无缝协同工作,恰恰印证了第一期提出的那个判断:一切皆数据,而这一切,都在一个数据库里。

下一期将进入时序数据库领域,介绍 TimescaleDB 扩展——看它如何让 PostgreSQL 支撑物联网监控、金融行情等海量时间序列数据的存储与分析。

参考文献

[1] Apache Ignite Wiki. PostgreSQL with pgvector: Storage Model and Indexing. 2026.

[2] Alibaba Cloud. PGVector for PolarDB Documentation. 2026.

[3] Supabase Docs. Going to Production with AI Applications. 2026.

[4] Encore. pgvector vs Qdrant: PostgreSQL Extension or Dedicated Vector Database. 2026.

[5] CSDN. 突破余弦相似度查询瓶颈:pgvector中HNSW索引的优化与限制. 2025.

[6] CSDN. 突破向量搜索性能瓶颈:PgVector索引选型与调优指南. 2025.

[7] Instaclustr. pgvector similarity search: Basics, tutorial and best practices. 2026.

[8] 网易. pgvector团队踩坑2周:600倍性能暴跌,竟因1个符号写错. 2026.

[9] AWS Database Blog. Supercharging vector search with pgvector 0.8.0 on Aurora. 2025.

[10] DbVisualizer. pgvectorscale: An Extension for Improved Vector Search in Postgres. 2025.

[11] Instaclustr. pgvector Hybrid Search: Benefits, Use Cases, and Quick Tutorial. 2025.

[12] Railway. Deploy PostgreSQL with pgvectorscale and pg_textsearch. 2025.

[13] CSDN. 5分钟搞定混合搜索:用pgvector打造智能问答系统. 2025.

[14] FOSS4G 2025. Semantic Spatial Search with Natural Language: Integrating NL2SQL with PostGIS & pgVector. 2025.

[15] YugabyteDB Docs. Hello RAG: Build a RAG pipeline with YugabyteDB. 2026.

[16] AWS Solutions. 高性能 RAG 聊天机器人构建指南. 2026.

[17] 腾讯云. PostgreSQL 17+:从向量能力爆发到 AI 原生. 2025.

[18] Pigsty Documentation. Intros to PostgreSQL Extensions — pgvector. 2026.

[19] pgvector GitHub Repository. README.md. Available at: https://github.com/pgvector/pgvector

Star
Donate
PostgreSQL 扩展生态全景解析(第二期):PostGIS —— 把数据库变成 GIS 背后的秘密
Previous
PostgreSQL 扩展生态全景解析(第四期):TimescaleDB —— 当 PostgreSQL 拥抱时间之河
Next

Leave a comment

Registration is not required

Clyde Jin
302 Articles
0 Comments
0 Like
Recent Posts

HiddenMerit Daily · Issue 59

📊 HiddenMerit Daily · Issue 59 Focus on Database Frontiers, Practical Insights for DBAs July 21, 2026 | 5 Selected Global Breaking News 01|Oracle Issues Urgent Warning: July 21 Release Update to Fix Large Number of High‑Risk Vulnerabilities, Immediate Deployment Recommended On July 13, Oracle issued an urgent security warning, strongly recommending that all customers running supported Oracle Database versions (including Oracle Database 19c and Oracle AI Database 26ai) immediately test and deploy the Release Update (RU) after its release on July 21. Background: New frontier AI models are significantly lowering the barrier to discovering and exploiting software vulnerabilities – these models can identify weaknesses, analyse software changes, reverse‑engineer security patches, and develop potential attack paths at unprecedented speed and scale. AI models are also becoming increasingly adept at combining multiple weaknesses across the application and data stack into complex attacks, even when individual weaknesses do not themselves pose a serious risk. As a result, protecting systems solely at the network or application layer is no longer sufficient; enterprises must protect the entire technology stack. Fixes Included in This RU: Oracle has collaborated with state‑of‑the‑art models from Anthropic and OpenAI to proactively identify and fix potential security vulnerabilities. The upcoming […]

HiddenMerit Daily · Issue 58

📊 HiddenMerit Daily · Issue 58 Focus on Database Frontiers, Practical Insights for DBAs July 20, 2026 | 5 Selected Global Breaking News 01|CAICT: Domestic Databases Enter Core System “Deep Water,” AI‑Native Leads New Industry Landscape On July 9, at the 2026 Trustworthy Database Development Conference, CAICT released the “Database Development Research Report (2026).” The report notes that domestic databases have basically completed peripheral system replacement and have officially entered the critical business system breakthrough phase. Key Data: The global database market reached $131.6 billion in 2025 (approximately RMB 894.09 billion). The Chinese database market reached $9.49 billion in 2025 (approximately RMB 64.48 billion), and is expected to reach RMB 97.974 billion by 2028, with a CAGR of 13.06%. The number of domestic database vendors has shrunk from a peak of 167 to 94, with a clear head‑concentration effect and an intensifying “Matthew effect.” AI‑Native Becomes the Main Theme: The report points out that database technology is accelerating its evolution toward the AI‑native direction, and the global database industry is entering a new phase of landscape restructuring. The role of databases is upgrading from “underlying support systems” to “core engines enabling intelligent decision‑making and business innovation.” AI agents are becoming […]

HiddenMerit Daily · Issue 56

📊 HiddenMerit Daily · Issue 56 Focus on Database Frontiers, Practical Insights for DBAs July 6, 2026 | 5 Selected Global Breaking News 01|Kingware Releases Manufacturing Scenario Database Evolution White Paper: SQL Server Replacement Enters “Deep Water” On July 5, CETC Kingware published a technical article titled “Database Evolution in Manufacturing Scenarios: How Kingware Replaces SQL Server,” pointing out that the data surge on industrial shop floors has exceeded the processing capacity of single‑node systems. Traditional database architectures that rely on vertical scaling are facing unprecedented performance challenges. Over the next 1‑3 years, manufacturing enterprises will no longer face only the “choice of replacement,” but must answer the strategic question: “How do we build an autonomous data foundation in the context of de‑IOE?” Three Paradigm Shifts: Hybrid Workloads Become the Norm: The IT architecture of modern factories is shifting from separated OLTP and OLAP to HTAP mode. The same data system must simultaneously handle tens of thousands of device instruction writes per second and minute‑level production report analysis. Distributed Architecture Becomes a Hard Requirement: When a single table exceeds 100 million rows with daily increments exceeding 1 million rows, the index maintenance cost of traditional single‑node databases rises exponentially. Autonomous […]

HiddenMerit Daily · Issue 57

📊 HiddenMerit Daily · Issue 57 Focus on Database Frontiers, Practical Insights for DBAs July 17, 2026 | 5 Selected Global Breaking News 01|CAICT Releases “Database Development Research Report (2026)”: China Market to Reach RMB 98 Billion by 2028, AI‑Native Becomes the Main Theme On July 9, at the 2026 Trustworthy Database Development Conference, the China Academy of Information and Communications Technology (CAICT) officially released the “Database Development Research Report (2026),” comprehensively revealing the latest landscape and evolution directions of the global and Chinese database markets. Key Data: Global Market: The global database market reached $131.6 billion in 2025 (approximately RMB 894.09 billion). Chinese Market: The Chinese database market reached $9.49 billion in 2025 (approximately RMB 64.48 billion), accounting for 7.2% of the global market. By 2028, the total Chinese database market is expected to reach RMB 97.974 billion, with a compound annual growth rate of 13.06% . Industry Landscape: There are 394 database product providers globally, with China and the US leading in vendor count. The number of global open‑source and closed‑source products is roughly balanced. Commercial databases account for over 70% in China, while the proportion of open‑source databases is increasing. After rapid growth from 2022 to 2024, […]
生成中...
扫描二维码
扫描二维码