本文档介绍了如何调整索引,以提高查询性能并提升检索率。
在构建 ScaNN
索引之前,请完成以下操作:
- 确保已创建包含数据的表。
- 请确保您为
maintenance_work_mem
和shared_buffers
标志设置的值小于机器总内存,以免在生成索引时出现问题。
调整 ScaNN
索引
请参考以下指南,在二级和三级 ScaNN 索引之间进行选择:
- 如果向量行数少于 1,000 万行,请选择两级索引。
- 如果向量行数超过 1 亿行,请选择三级索引。
- 如果矢量行数介于 1,000 万到 1 亿行之间,请选择三级索引以优化索引构建时间;如果矢量行数介于 1,000 万到 1 亿行之间,请选择二级索引以优化搜索召回率。
请考虑以下针对两级和三级 ScaNN
索引的示例,它们展示了如何为包含 1000000 行的表设置调整参数:
两级索引
SET LOCAL scann.num_leaves_to_search = 1;
SET LOCAL scann.pre_reordering_num_neighbors=50;
CREATE INDEX my-scann-index ON my-table
USING scann (vector_column cosine)
WITH (num_leaves = [power(1000000, 1/2)]);
三级索引
SET LOCAL scann.num_leaves_to_search = 10;
SET LOCAL scann.pre_reordering_num_neighbors=50;
CREATE INDEX my-scann-index ON my-table
USING scann (vector_column cosine)
WITH (num_leaves = [power(1000000, 2/3)], max_num_levels = 2);
分析查询
使用 EXPLAIN ANALYZE
命令分析查询数据分析,如以下 SQL 查询示例所示。
EXPLAIN ANALYZE SELECT result-column
FROM my-table
ORDER BY EMBEDDING_COLUMN <-> embedding('text-embedding-005', 'What is a database?')::vector
LIMIT 1;
示例响应 QUERY PLAN
包含所用时间、扫描或返回的行数以及使用的资源等信息。
Limit (cost=0.42..15.27 rows=1 width=32) (actual time=0.106..0.132 rows=1 loops=1)
-> Index Scan using my-scann-index on my-table (cost=0.42..858027.93 rows=100000 width=32) (actual time=0.105..0.129 rows=1 loops=1)
Order By: (embedding_column <-> embedding('text-embedding-005', 'What is a database?')::vector(768))
Limit value: 1
Planning Time: 0.354 ms
Execution Time: 0.141 ms
查看向量索引指标
您可以使用向量索引指标来查看向量索引的性能、确定需要改进的方面,并根据需要根据指标调整索引。
如需查看所有矢量索引指标,请运行以下使用 pg_stat_ann_indexes
视图的 SQL 查询:
SELECT * FROM pg_stat_ann_indexes;
您将看到类似如下所示的输出:
-[ RECORD 1 ]----------+---------------------------------------------------------------------------
relid | 271236
indexrelid | 271242
schemaname | public
relname | t1
indexrelname | t1_ix1
indextype | scann
indexconfig | {num_leaves=100,quantizer=SQ8}
indexsize | 832 kB
indexscan | 0
insertcount | 250
deletecount | 0
updatecount | 0
partitioncount | 100
distribution | {"average": 3.54, "maximum": 37, "minimum": 0, "outliers": [37, 12, 11, 10, 10, 9, 9, 9, 9, 9]}
distributionpercentile |{"10": { "num_vectors": 0, "num_partitions": 0 }, "25": { "num_vectors": 0, "num_partitions": 30 }, "50": { "num_vectors": 3, "num_partitions": 30 }, "75": { "num_vectors": 5, "num_partitions": 19 }, "90": { "num_vectors": 7, "num_partitions": 11 }, "95": { "num_vectors": 9, "num_partitions": 5 }, "99": { "num_vectors": 12, "num_partitions": 4 }, "100": { "num_vectors": 37, "num_partitions": 1 }}
如需详细了解指标的完整列表,请参阅矢量索引指标。