調整 AlloyDB for PostgreSQL 中的向量查詢效能

瞭解如何調整下列向量索引,在 PostgreSQL 適用的 AlloyDB 中提升查詢效能並改善召回率:

您也可以分析查詢並查看向量索引指標,藉此監控及提升查詢效能。

調整 HNSW 索引

調整為 mef_constructionhnsw.ef_search 參數設定的值,有助於提升應用程式效能。

調整參數 說明 參數類型
m 圖表中每個節點的連線數量上限。您可以從預設值 16(預設) 開始,並根據資料集大小嘗試使用較高的值。 建立索引
ef_construction 圖表建構期間維護的動態候選清單大小,會不斷更新節點的最近鄰項目前最佳候選項目。將這個值設為大於 m 值的兩倍,例如 64(預設值)。 建立索引
ef_search 搜尋期間使用的動態候選名單大小。您可以先將這個值設為 mef_construction,然後在觀察召回率時變更這個值。預設值為 40 查詢執行階段

請參考以下範例,瞭解如何設定調整參數的 hnsw 索引:

SET LOCAL hnsw.ef_search = 40;

CREATE INDEX my-hnsw-index ON my-table
  USING hnsw (vector_column cosine)
  WITH (m = 16, ef_construction = 200);

分析查詢

使用 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

查看向量索引指標

您可以運用向量索引指標查看向量索引的成效、找出可改進的部分,並視需要根據指標調整索引。

如要查看所有向量索引指標,請執行下列 SQL 查詢,其中會使用 pg_stat_ann_indexes 檢視區塊:

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 }}

如要進一步瞭解完整的指標清單,請參閱「向量索引指標」。

後續步驟