本文是「pgvector 源码内核」赛道 L2 阶段的第二篇。同阶段上一篇:
类型适配表:HnswTypeInfo 与 IvfflatTypeInfo同赛道的 L1 阶段:
四种向量类型的内存布局、
距离算子与 SIMD 分派本文所有行号基于
/Users/growduduan/cwork/pgvector,git describe=v0.8.7-147-g11d2b80,HEAD =11d2b80。本文不讨论:HNSW 图怎么建(L3)、IVFFlat 的 k-means 怎么跑(L4)、
SQL 表面与运维(L5)。
这里只回答:PostgreSQL 眼里,pgvector 的索引是个什么东西。
4.1 接入点只有一个函数
PostgreSQL 的索引访问方法(index access method,简称 AM)是一个
填满的函数指针结构体。扩展通过一个 handler 函数把它交出来。
sql/vector.sql 里:
CREATE FUNCTION hnswhandler(internal) RETURNS index_am_handler
AS 'MODULE_PATHNAME' LANGUAGE C;
对应的 C 函数在 src/hnsw.c:466-527:
FUNCTION_PREFIX PG_FUNCTION_INFO_V1(hnswhandler);
Datum
hnswhandler(PG_FUNCTION_ARGS)
{
#if PG_VERSION_NUM >= 190000
static const IndexAmRoutine amroutine = {
.type = T_IndexAmRoutine,
.amstrategies = 0,
.amsupport = HNSW_NPROCS,
...
};
PG_RETURN_POINTER(&amroutine);
#else
IndexAmRoutine *amroutine = makeNode(IndexAmRoutine);
...
#endif
}
PG 19 与更早版本走两条路:
- PG 19+:用静态 const 结构体 + 指定初始化器(designated initializer);
- 更早版本:用
makeNode()动态分配,然后逐字段赋值。
原因是 PG 19 的 IndexAmRoutine 新增了字段,
静态初始化器在编译期就会因为缺字段而报错——
这等于强制扩展作者在新版 PostgreSQL 上更新代码。
动态分配则只在你用到新字段时才需要改。
(同样的模式在 src/ivfflat.c:388-513 里,ivfflathandler 是老版本的写法。)
4.2 标志位:ANN 索引的「能力清单」
IndexAmRoutine 里有几十个布尔字段。挑几个关键的看。
4.2.1 amcanorderbyop = true,amcanorder = false
.amcanorder = false,
.amcanorderbyop = true,
这两个字段的区别是 ANN 索引最容易被误解的地方。
| 字段 | 含义 |
|---|---|
amcanorder |
索引本身能按顺序返回元组(比如 B-tree 的顺序扫描) |
amcanorderbyop |
索引能按某个算子排序(ORDER BY col <-> query) |
B-tree 两个都是 true。HNSW 只有 amcanorderbyop 是 true。
为什么 amcanorder 必须是 false?
因为 HNSW 图没有顺序。你没法说「按索引顺序返回」——
图的遍历顺序取决于查询向量。
为什么 amcanorderbyop 是 true?
因为它能按距离排序:ORDER BY embedding <-> '[1,2,3]' LIMIT 10,
索引能给出按距离从小到大的结果。
关键区别:amcanorderbyop = true 不等于索引返回的顺序
等于 ORDER BY 要求的顺序。ANN 索引返回的是近似的最近邻,
它只是「看起来像排过序」,PostgreSQL 因此会把它当作ORDER BY 已满足(不再额外排序)。
这就是为什么 pgvector 的索引不能和 ORDER BY 其它列混用——
它只能在整个 ORDER BY 里提供唯一的那一列。
4.2.2 amoptionalkey = true
.amoptionalkey = true,
索引扫描可以不带任何 key。
B-tree 不行——没有 key 就没法定位。
但 HNSW 可以:SELECT * FROM items ORDER BY embedding <-> '[1,2,3]' LIMIT 10
不带 WHERE,索引照样能用(全表扫描 + 排序)。
这个标志告诉 PostgreSQL:别因为「没有扫描条件」就排除掉这个索引。
4.2.3 amcanparallel = false,amcanbuildparallel = true
.amcanparallel = false,
.amcanbuildparallel = true,
并行扫描不支持,但并行构建支持。
- 不能并行扫描:HNSW 的图遍历是有状态的
(候选堆、visited 集合、当前层),
把图分给多个 worker 各自走一遍,结果合起来不是「最近邻」,
而是「多个局部最近邻的并集」。语义不对。 - 能并行构建:构建是「每个 worker 各自建自己的图,
最后合并」,合并后的图仍然合法。L3 会讲合并怎么做的。
4.2.4 amcanbackward = false
.amcanbackward = false, /* can change direction mid-scan */
索引扫描不能反向。ORDER BY embedding <-> q DESC 用不了索引。
4.2.5 amcanunique = false,amcanmulticol = false
.amcanunique = false,
.amcanmulticol = false,
- 不是唯一索引:
CREATE UNIQUE INDEX ... USING hnsw会报错; - 不支持多列:
USING hnsw (a, b)会报错。
4.2.6 amcaninclude = false
.amcaninclude = false,
不支持 INCLUDE 子句。pgvector 0.8.0 加过这个功能又……实际上当前版本
不支持——写 INCLUDE 会报错。
4.2.7 amstrategies = 0,amsupport = 3(HNSW)/ 5(IVFFlat)
.amstrategies = 0,
.amsupport = HNSW_NPROCS,
amstrategies = 0:索引没有策略号。
B-tree 有 5 个(<<==>=>)。ANN 索引的距离比较
不通过「扫描 key」实现,而是通过 opfamily 里的算子。amsupport = 3/5:索引有 3 个 / 5 个 support function 槽位。
HNSW 的三个槽位(src/hnsw.h:47-50):
#define HNSW_DISTANCE_PROC 1
#define HNSW_NORM_PROC 2
#define HNSW_TYPE_INFO_PROC 3
#define HNSW_NPROCS 3
IVFFlat 的五个(src/ivfflat.h:45-50):
#define IVFFLAT_DISTANCE_PROC 1
#define IVFFLAT_NORM_PROC 2
#define IVFFLAT_KMEANS_DISTANCE_PROC 3
#define IVFFLAT_KMEANS_NORM_PROC 4
#define IVFFLAT_TYPE_INFO_PROC 5
#define IVFFLAT_NPROCS 5
IVFFlat 比 HNSW 多两个:k-means 需要自己的距离与范数函数。vector_cosine_ops 的 ivfflat 版本里:
CREATE OPERATOR CLASS vector_cosine_ops
FOR TYPE vector USING ivfflat AS
OPERATOR 1 <=> (vector, vector) FOR ORDER BY float_ops,
FUNCTION 1 vector_negative_inner_product(vector, vector),
FUNCTION 2 vector_norm(vector),
FUNCTION 3 vector_spherical_distance(vector, vector),
FUNCTION 4 vector_norm(vector),
FUNCTION 5 ...;
FUNCTION 3 是 vector_spherical_distance——k-means 专用的距离
(就是 L1 讲的 acos(内积)/π,满足三角不等式那个)。
普通扫描用 FUNCTION 1(内积),k-means 用 FUNCTION 3(球面距离)——
两个不同的度量,这就是为什么 IVFFlat 需要两套。
4.2.8 amparallelvacuumoptions
.amparallelvacuumoptions = VACUUM_OPTION_PARALLEL_BULKDEL,
支持并行 vacuum 的 bulk delete 阶段。
批量删除元素是逐个独立的事,可以并行;重写邻接表不行。
4.2.9 amkeytype = InvalidOid
索引没有「key 类型」——它不用 scan key 做定位。
4.3 amvalidate:opclass 的合法性检查
hnswvalidate(src/hnsw.c:285-464)在 CREATE OPERATOR CLASS
或 ALTER OPERATOR FAMILY 时跑,检查 opfamily 里的算子与函数是否合规。
4.3.1 策略号必须是 1
/* Check strategy number */
if (oprform->amopstrategy != 1)
{
ereport(INFO,
(errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
errmsg("operator family \"%s\" of access method %s contains operator %s with invalid strategy number %d",
opfamilyname, "hnsw",
format_operator(oprform->amopopr),
oprform->amopstrategy)));
result = false;
}
ANN 索引只允许一个策略号(就是 1)。
因为 amstrategies = 0——没有多策略的概念。
策略号 1 对应 opclass 里那个唯一的距离算子
(OPERATOR 1 <-> ... FOR ORDER BY float_ops)。
4.3.2 算子签名必须是 (T, T) → float8
/* Check operator signature */
if (!check_amop_signature(oprform->amopopr, FLOAT8OID, opcintype, opcintype))
{
ereport(INFO, ... errmsg("operator family \"%s\" of access method %s contains operator %s with wrong signature", ...));
result = false;
}
距离算子必须左右都是同类型、返回 float8。
注意算子还要声明 FOR ORDER BY float_ops:
/* Check sort family */
if (oprform->amoppurpose != AMOP_ORDER || !opfamily_can_sort_type(oprform->amopsortfamily, FLOAT8OID))
{
ereport(INFO, ... errmsg("operator family \"%s\" of access method %s contains invalid ORDER BY specification for operator %s", ...));
result = false;
}
两件事:算子的 purpose 必须是 AMOP_ORDER(专门给 ORDER BY 用的),
它声明的排序族必须能排 float8。
4.3.3 support function 的签名检查
switch (procform->amprocnum)
{
case HNSW_DISTANCE_PROC:
ok = check_amproc_signature(procform->amproc, FLOAT8OID, true, 2, 2, opcintype, opcintype);
break;
case HNSW_NORM_PROC:
ok = check_amproc_signature(procform->amproc, FLOAT8OID, true, 1, 1, opcintype);
break;
case HNSW_TYPE_INFO_PROC:
ok = check_amproc_signature(procform->amproc, INTERNALOID, true, 1, 1, INTERNALOID);
break;
default:
ereport(INFO, ... errmsg("... contains function %s with invalid support number %d", ...));
result = false;
continue;
}
三个槽位各有各的签名要求:
| 槽位 | 返回 | 参数个数 | 参数类型 |
|---|---|---|---|
| FUNCTION 1(距离) | float8 |
2 | (T, T) |
| FUNCTION 2(范数) | float8 |
1 | (T) |
| FUNCTION 3(类型信息) | internal |
0 | — |
注意 FUNCTION 3 的参数个数是 0——check_amproc_signature(procform->amproc, INTERNALOID, true, 1, 1, INTERNALOID)
最后两个 1, 1 是「proc 参数个数」(1 个 internal)
和「真正的参数个数」(也是 1)。
这是因为 SQL 层的 support function 固定带一个 internal 参数。
回头看 hnsw_halfvec_support 的实现(src/hnswutils.c:1664-1678):
它的 PG_FUNCTION_ARGS 里确实一个参数都没用——
但签名上它有那个 internal 参数。
4.3.4 还要检查左右类型一致
/* Check matching left/right types */
if (procform->amproclefttype != procform->amprocrighttype)
{
ereport(INFO, ... errmsg("operator family \"%s\" of access method %s contains support function %s with different left and right input types", ...));
result = false;
}
if (procform->amproclefttype != opcintype)
continue;
第二个 if 是关键:只有 lefttype == opcintype 的函数才检查签名。
因为一个 opfamily 里可能有多个类型的算子(比如 vector_ops 和 halfvec_ops
在同一个 family 里),每个类型只需要检查自己那部分。
所有错误都用 ereport(INFO) 而不是 ereport(ERROR)——
收集完所有问题再一起报。result 标志一路累积,
最后统一返回 false 或 true。
4.4 参数:reloption 与 GUC
两个索引的参数分两类:建索引时定死的(reloption)
与查询时可调的(GUC)。
4.4.1 HNSW 的 reloption
src/hnsw.c:96-100:
hnsw_relopt_kind = add_reloption_kind();
add_int_reloption(hnsw_relopt_kind, "m", "Max number of connections",
HNSW_DEFAULT_M, HNSW_MIN_M, HNSW_MAX_M, AccessExclusiveLock);
add_int_reloption(hnsw_relopt_kind, "ef_construction", "Size of the dynamic candidate list for construction",
HNSW_DEFAULT_EF_CONSTRUCTION, HNSW_MIN_EF_CONSTRUCTION, HNSW_MAX_EF_CONSTRUCTION, AccessExclusiveLock);
| 参数 | 默认 | 范围 | 何时定 |
|---|---|---|---|
m |
16 | 2–100 | 建索引时 |
ef_construction |
64 | 4–1000 | 建索引时 |
这两个参数写进索引的元页,建完之后不能改
(HnswMetaPageData 里有 m 和 efConstruction 字段)。
m 是「每个节点最多连几条边」;ef_construction 是
「建图时候选队列的大小」。
4.4.2 HNSW 的 GUC
src/hnsw.c:102-120:
DefineCustomIntVariable("hnsw.ef_search", "Sets the size of the dynamic candidate list for search",
"Valid range is 1..1000.", &hnsw_ef_search,
HNSW_DEFAULT_EF_SEARCH, HNSW_MIN_EF_SEARCH, HNSW_MAX_EF_SEARCH, PGC_USERSET, GUC_EXPLAIN, NULL, NULL, NULL);
DefineCustomEnumVariable("hnsw.iterative_scan", "Sets the mode for iterative scans",
NULL, &hnsw_iterative_scan,
HNSW_ITERATIVE_SCAN_OFF, hnsw_iterative_scan_options, PGC_USERSET, GUC_EXPLAIN, NULL, NULL, NULL);
/* This is approximate and does not affect the initial scan */
DefineCustomIntVariable("hnsw.max_scan_tuples", "Sets the max number of tuples to visit for iterative scans",
NULL, &hnsw_max_scan_tuples,
20000, 1, INT_MAX, PGC_USERSET, GUC_EXPLAIN, NULL, NULL, NULL);
/* Same range as hash_mem_multiplier */
DefineCustomRealVariable("hnsw.scan_mem_multiplier", "Sets the multiple of work_mem to use for iterative scans",
NULL, &hnsw_scan_mem_multiplier,
1, 1, 1000, PGC_USERSET, GUC_EXPLAIN, NULL, NULL, NULL);
MarkGUCPrefixReserved("hnsw");
| GUC | 默认 | 范围 | 作用 |
|---|---|---|---|
hnsw.ef_search |
40 | 1–1000 | 查询时的候选队列大小 |
hnsw.iterative_scan |
off |
off / relaxed_order / strict_order |
迭代扫描模式 |
hnsw.max_scan_tuples |
20000 | 1–INT_MAX |
迭代扫描的元组上限 |
hnsw.scan_mem_multiplier |
1 | 1–1000 | 迭代扫描的内存倍数 |
hnsw.ef_search 是最常调的那个:调大召回率上升、延迟上升;
调小反之。它是查询时的旋钮,不用重建索引。
hnsw.iterative_scan 的三个取值(src/hnsw.h:155-160):
typedef enum HnswIterativeScanMode
{
HNSW_ITERATIVE_SCAN_OFF,
HNSW_ITERATIVE_SCAN_RELAXED,
HNSW_ITERATIVE_SCAN_STRICT
} HnswIterativeScanMode;
迭代扫描解决的是这个问题:LIMIT 10 但过滤器只留下 2 条符合条件的,
ANN 索引返回的 10 条里有 8 条被过滤掉了,结果不满 10 条。
迭代扫描会继续往下扫,直到凑够 10 条或达到上限。
relaxed_order:凑够就行,不保证顺序严格正确;strict_order:保证返回的是真正的 top-k,代价是扫更多。
hnsw.max_scan_tuples 的注释很有意思:
“This is approximate and does not affect the initial scan”——
它只限制迭代阶段扫多少,不影响第一轮扫描。
MarkGUCPrefixReserved("hnsw") —— 保留 hnsw. 前缀,
防止别的扩展用同名 GUC 撞车。
4.4.3 IVFFlat 的参数
src/ivfflat.c:46-70:
ivfflat_relopt_kind = add_reloption_kind();
add_int_reloption(ivfflat_relopt_kind, "lists", "Number of inverted lists",
IVFFLAT_DEFAULT_LISTS, IVFFLAT_MIN_LISTS, IVFFLAT_MAX_LISTS, AccessExclusiveLock);
DefineCustomIntVariable("ivfflat.probes", "Sets the number of probes",
"Valid range is 1..lists.", &ivfflat_probes,
IVFFLAT_DEFAULT_PROBES, IVFFLAT_MIN_LISTS, IVFFLAT_MAX_LISTS, PGC_USERSET, GUC_EXPLAIN, NULL, NULL, NULL);
DefineCustomEnumVariable("ivfflat.iterative_scan", "Sets the mode for iterative scans",
NULL, &ivfflat_iterative_scan,
IVFFLAT_ITERATIVE_SCAN_OFF, ivfflat_iterative_scan_options, PGC_USERSET, GUC_EXPLAIN, NULL, NULL, NULL);
/* If this is less than probes, probes is used */
DefineCustomIntVariable("ivfflat.max_probes", "Sets the max number of probes for iterative scans",
NULL, &ivfflat_max_probes,
IVFFLAT_MAX_LISTS, IVFFLAT_MIN_LISTS, IVFFLAT_MAX_LISTS, PGC_USERSET, GUC_EXPLAIN, NULL, NULL, NULL);
| 参数 | 类型 | 默认 | 范围 |
|---|---|---|---|
lists |
reloption | 100 | 1–32768 |
ivfflat.probes |
GUC | 1 | 1–32768 |
ivfflat.iterative_scan |
GUC | off |
off / relaxed_order |
ivfflat.max_probes |
GUC | 32768 | 1–32768 |
lists 是建索引时定的(倒排表的个数),probes 是查询时定的
(每次查询探几个 list)。
ivfflat.max_probes 的默认是 32768(即 IVFFLAT_MAX_LISTS),
注释说 “If this is less than probes, probes is used”——
如果 max_probes < probes,实际用 probes。
所以「最多探多少」永远不会比「最少探多少」还小。
IVFFlat 的迭代扫描只有 off 和 relaxed_order——
没有 strict_order:
static const struct config_enum_entry ivfflat_iterative_scan_options[] = {
{"off", IVFFLAT_ITERATIVE_SCAN_OFF, false},
{"relaxed_order", IVFFLAT_ITERATIVE_SCAN_RELAXED, false},
{NULL, 0, false}
};
为什么没有 strict?
HNSW 的图遍历是逐层下降的,严格顺序意味着「要保证 top-k 就得一直扫到
第 k 个候选确认为止」;IVFFlat 的 list 是互相独立的,
探下一个 list 就是在扩大候选集,顺序上更接近「探过的 list 里取最优」,
做严格保证的代价与收益不成比例。
(src/ivfflat.h:107-111 也印证了这点:
typedef enum IvfflatIterativeScanMode
{
IVFFLAT_ITERATIVE_SCAN_OFF,
IVFFLAT_ITERATIVE_SCAN_RELAXED
} IvfflatIterativeScanMode;
只有两个值。)
4.4.4 两组参数的对照
| HNSW | IVFFlat | |
|---|---|---|
| 建索引时 | m(16)、ef_construction(64)、lists(100) |
lists(100) |
| 查询时 | ef_search(40)、iterative_scan |
probes(1)、iterative_scan |
| 存储单元 | 元素元组 + 邻接元组 | list 元组 + 元素元组 |
HNSW 建索引时的两个参数都影响图的形状(m 决定图有多密,ef_construction 决定建图质量),IVFFlat 的 lists 只决定分桶粒度。
查询时 HNSW 调 ef_search(队列大小)、IVFFlat 调 probes(探几个桶)——
这是两种 ANN 索引最本质的差别:
HNSW 是「在图里走多远」,IVFFlat 是「看几个桶」。
4.5 成本估算:为什么规划器会选它
两个索引都实现了 amcostestimate。这个函数决定 PostgreSQL 的规划器
会不会用这个索引——写错了,索引建了也不用。
4.5.1 共同的第一步:没有 ORDER BY 就不给用
两处代码一模一样:
/* Never use index without order */
if (path->indexorderbys == NIL)
{
*indexStartupCost = get_float8_infinity();
*indexTotalCost = get_float8_infinity();
*indexSelectivity = 0;
*indexCorrelation = 0;
*indexPages = 0;
#if PG_VERSION_NUM >= 180000
/* See "On disable_cost" thread on pgsql-hackers */
path->path.disabled_nodes = 2;
#endif
return;
}
(src/hnsw.c:157-171、src/ivfflat.c:109-123)
成本设成无穷大 —— 规划器绝不会选它。
ANN 索引只能提供「按距离排序」的结果,SELECT * FROM items WHERE category = 'x' 这种查询它帮不上忙
(它不存 category)。
PG 18+ 还额外设了 disabled_nodes = 2,
让规划器彻底不考虑这个路径(不只是成本高)。
4.5.2 HNSW 的估算公式
src/hnsw.c:184-224 的注释把公式讲得很清楚:
numIndexTuples = entryLevel * m + layer0TuplesMax * layer0Selectivity
代码:
if (tuples > 0)
{
double scalingFactor = 0.55;
int entryLevel = (int) (log(tuples) * HnswGetMl(m));
int layer0TuplesMax = HnswGetLayerM(m, 0) * hnsw_ef_search;
double layer0Selectivity = scalingFactor * log(tuples) / (log(m) * (1 + log(hnsw_ef_search)));
ratio = (entryLevel * m + layer0TuplesMax * layer0Selectivity) / tuples;
if (ratio > 1)
ratio = 1;
}
三项的含义(照注释):
entryLevel * m——「降到 L0 需要扫多少元组」。entryLevel = log(tuples) * HnswGetMl(m),HnswGetMl(m) = 1 / log(m)(src/hnsw.h:128,论文里的最优 ml)。
每层扫m个点,所以是entryLevel * m;layer0TuplesMax—— 「L0 层最多要扫多少元组」。HnswGetLayerM(m, 0)是 L0 的连接数(m * 2,见src/hnsw.h:125),
乘以ef_search;layer0Selectivity—— 「考虑已访问去重后,实际扫的比例」,
乘一个硬编码的scalingFactor = 0.55。
注释里对这个硬编码值是明说的:
Currently, we use a hardcoded scaling factor (HNSWScanScalingFactor) to help influence that, but this could later become a configurable parameter based on the cost estimations.
0.55 是拍出来的经验值——它把「扫了多少元组」换算成
「实际读了几个 page」,用来修正随机读与顺序读的成本差。
4.5.3 IVFFlat 的估算公式
src/ivfflat.c:138-148:
/* Get the ratio of lists that we need to visit */
ratio = ((double) ivfflat_probes) / lists;
if (ratio > 1.0)
ratio = 1.0;
简单得多:扫多少 list 就是 probes / lists 的比例。
接着有一段成本调整:
/* Change some page cost from random to sequential */
costs.indexTotalCost -= sequentialRatio * costs.numIndexPages * (costs.spc_random_page_cost - costs.spc_seq_page_cost);
sequentialRatio = 0.5——假设一半的页访问是顺序的。
因为 IVFFlat 的每个 list 内部是按插入顺序追加的,
读一个 list 相当于顺序读一段。
4.6 两个索引的结构对照
| 维度 | HNSW | IVFFlat |
|---|---|---|
| 数据结构 | 分层图 | 倒排 list |
| 元页存什么 | m、efConstruction、dimensions、入口点 |
dimensions、lists |
| 每个元素的存储 | 元素元组 + 邻接元组 | 元素元组(挂在 list 的链上) |
| 插入要做的事 | 找邻居、连双向边 | 找最近的 list 中心、追加 |
| 查询要做的事 | 从入口点逐层下降 | 探 probes 个 list |
| 内存占用 | 大(图本身) | 小(只有中心点) |
| 能否并行扫描 | ❌ | ❌ |
| 能否并行构建 | ✅ | ✅ |
元页的差别很有代表性:
typedef struct HnswMetaPageData
{
uint32 magicNumber;
uint32 version;
uint32 dimensions;
uint16 m;
uint16 efConstruction;
BlockNumber entryBlkno;
OffsetNumber entryOffno;
int16 entryLevel;
BlockNumber insertPage;
} HnswMetaPageData;
typedef struct IvfflatMetaPageData
{
uint32 magicNumber;
uint32 version;
uint16 dimensions;
uint16 lists;
} IvfflatMetaPageData;
HNSW 的元页要存入口点(entryBlkno / entryOffno / entryLevel)
——因为图遍历必须从某个点开始。
IVFFlat 的元页只存维度与 list 数——
list 的中心点在 list 自己的元组里,不用在元页记。
magicNumber 是识别索引类型的凭据:HNSW_MAGIC_NUMBER = 0xA953A953,IVFFLAT_MAGIC_NUMBER = 0x14FF1A7。
页的 opaque data 里还有一个 page_id:HNSW_PAGE_ID = 0xFF90,IVFFLAT_PAGE_ID = 0xFF84。
这是给「这个页属于哪个索引」的快速判断用的——
读到一个页,先看 page_id 对不对,不对就说明索引文件坏了。
4.7 边界与小结
本文只讲索引访问方法这一层。它没讲:
- HNSW 图怎么建、怎么查 → L3「HNSW 分层图」
- IVFFlat 的 k-means 与 list 分配 → L4「IVFFlat 倒排」
- 完整的 SQL 表面 → L5「SQL 表面与运维」
八条带走的:
- 接入点只有两个 handler 函数:
hnswhandler/ivfflathandler,返回IndexAmRoutine。
PG 19+ 用静态 const 结构体,更早版本用makeNode逐字段赋值。 amcanorderbyop = true而amcanorder = false:
ANN 索引没有顺序,但能「按距离排序」。
这意味着它不能和ORDER BY的其它列混用。amstrategies = 0:ANN 索引没有策略号,距离算子固定是策略 1。amsupport是 3(HNSW)/ 5(IVFFlat):
IVFFlat 多出的两个是 k-means 专用的距离与范数。amvalidate用ereport(INFO)收集所有问题再一起报,
签名要求:距离(T,T)→float8、范数(T)→float8、类型信息()→internal。- 参数分两类:reloption 建索引时定死(
m/ef_construction/lists),
GUC 查询时可调(ef_search/probes/iterative_scan)。 - IVFFlat 的迭代扫描没有
strict_order,只有off和relaxed_order。 - 没有
ORDER BY就把成本设成无穷大:
ANN 索引只能服务「按距离排序」这一种查询形态;
HNSW 的成本估算里那个0.55是硬编码的经验值,源码注释里明说了。
引用
本文涉及的字段、宏与常量,均取自 pgvector 源码
(/Users/growduduan/cwork/pgvector,git describe = v0.8.7-147-g11d2b80,
HEAD = 11d2b80,核对时间:2026-12-04):
| 事实 | 出处 |
|---|---|
hnswhandler 与 IndexAmRoutine 的 PG19 / 老版本两条路 |
src/hnsw.c:466-527 |
ivfflathandler 的 amroutine 字段赋值 |
src/ivfflat.c:388-513 |
| HNSW 的 amroutine 标志位 | src/hnsw.c:471-524 |
amvalidate 的策略号 / 算子签名 / support function 签名检查 |
src/hnsw.c:285-424 |
check_amproc_signature 的三组签名要求 |
src/hnsw.c:351-371 |
lefttype != opcintype 时跳过签名检查 |
src/hnsw.c:347-348 |
| HNSW 的 reloption 与 GUC 定义 | src/hnsw.c:96-120 |
hnsw.iterative_scan 的三个取值 |
src/hnsw.c:37-42、src/hnsw.h:155-160 |
HnswGetMl / HnswGetLayerM |
src/hnsw.h:125-128 |
| HNSW 成本估算公式与 0.55 的说明 | src/hnsw.c:184-224 |
| IVFFlat 的 reloption 与 GUC 定义 | src/ivfflat.c:46-70 |
ivfflat.max_probes 与 probes 的关系注释 |
src/ivfflat.c:65-67 |
| IVFFlat 迭代扫描只有两个取值 | src/ivfflat.c:38-43、src/ivfflat.h:107-111 |
| IVFFlat 成本估算的 ratio 与 sequentialRatio | src/ivfflat.c:138-148 |
| 两处「没有 ORDER BY 就设成无穷大」 | src/hnsw.c:157-171、src/ivfflat.c:109-123 |
HnswMetaPageData 与 IvfflatMetaPageData |
src/hnsw.h:353-364、src/ivfflat.h:253-259 |
HNSW_MAGIC_NUMBER / HNSW_PAGE_ID / IVFFlat 对应常量 |
src/hnsw.h:52-58、src/ivfflat.h:52-58 |
| support function 槽位编号 | src/hnsw.h:47-50、src/ivfflat.h:45-50 |
| opclass 里各 FUNCTION 的分配 | sql/vector.sql |