#846·pgvector

在没有 LIMIT 或 enable_indexscan 的 ANN 查询中意外使用索引扫描

作者: developerayuva创建于 2025年5月26日更新于 2026年2月11日

你们好 我观察到一些意外的行为 当使用矢量扩展 与分割表和HNSW索引。 我想澄清为什么在一种情况下使用指数扫描,而在另一种情况下却不使用,尽管有类似的查询模式。

□ 案例一

脚本QQ\d+ 向量  collection2
分区表“ public.vector  collection2 ”
分栏 分栏 分栏 分栏 分栏 分栏 分栏 分栏 分栏 分栏 分栏 分栏 分会 分会 分会 分会 分会 分会 分会 分会
-------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ ----------------------------------------------
id=整数======================================================================================
嵌入 QQ 向量 (5) QQ 外出 QQ 外出
分区键: HASH (id)
索引 :
(原始内容存档于2013-10-12) (中文(简体) ). Restor collection2 pkey" Primary nucture, btree (id)
"vector collection2 embedding idx" hnsw(mbedding 向量 l2 ops)与(m='8',ef building='16')相接.
分区:矢量-收集2 ts00001 用于从(MINVALUE)到('-6917529027641081856')的VALUES,
从('-6917529027641081856')到('-4611686018427387904'),
矢量 收集2 ts00003 为 VALUES 从 ('-4611686018427387904') 到 ('-2305843009213693952'),
VALUES 从 ('' 2305843009213693952') 到 ('0')

脚本 QQ 重置启用  seqscan ;
续
脚本 QQ 重置启用  indexscan ;
续
脚本 QQ SELECT COUNT( *) 从向量  collection2;
计数
- - - - - - - - ----
4997869 (英语).
(第1行)

-- 获取 ID 和嵌入
脚本 解释分析 SELECT id, 从 public.vector collection2 ORDER BY (嵌入 OPERATOR (public. <- >)) ' [0.08761761,0.16212644,0.061548516,0.099646576,0.36062342]' : public.vector) ASC NULLS LAST;
快速计划
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -----------------
合并后追加(成本=262.30.875089.46行=4997869宽=37) (实际时间=3.000.37.168行=160回环=1).
排序键 :( (vector collection2.embedding <- > ) [0.08761761,0.16212644,0.061548516,0.099646576,0.36062342]':vector).
- > Index scan 使用向量 collection2 ts0001 嵌入 idx 在向量上 collection2 ts0001 向量 collection2 1 (cost=65.57.199836.08行=1248204宽=37 (实际时间=0.651.19.815行=40环=1)
顺序为: (嵌入"-" [0.08761761, 0.16212644, 0.061548516, 0.099646576, 0.36062342]" : vector)
- > Index scan 使用向量 collection2 ts0002 嵌入 idx 在向量上 collection2 ts0002 向量 collection2 2(成本=65.57.200180.46行=1250423宽=37 (实际时间=0.725.5. 5.305行=40回环=1)
顺序 : (嵌入 <->)
. . . . . . .

内容来源: pgvector/pgvector