> Discover all available pages from the documentation index: https://mastra.zisheng.pro/zh-HK/llms.txt # PG 向量儲存 PgVector 類別使用配備 [pgvector](https://github.com/pgvector/pgvector) 擴充功能的 [PostgreSQL](https://www.postgresql.org/) 提供向量搜尋。 它在你現有的 PostgreSQL 資料庫內提供可靠的向量相似度搜尋功能。 ## 建構函數選項 **connectionString** (`string`): PostgreSQL 連線 URL **host** (`string`): PostgreSQL 伺服器主機 **port** (`number`): PostgreSQL 伺服器連接埠 **database** (`string`): PostgreSQL 資料庫名稱 **user** (`string`): PostgreSQL 使用者 **password** (`string`): PostgreSQL 密碼 **ssl** (`boolean | ConnectionOptions`): 啟用 SSL 或提供自訂 SSL 配置 **schemaName** (`string`): 你希望向量儲存使用的 schema 名稱。如未提供,將使用預設 schema。 **max** (`number`): 連線池的連線數目上限(預設:20) **idleTimeoutMillis** (`number`): 閒置連線逾時(毫秒)(預設:30000) **pgPoolOptions** (`PoolConfig`): 其他 pg 連線池配置選項 **disableInit** (`boolean`): 設為 true 時,會略過 createIndex 內的自動 DDL(建立 schema、擴充功能、資料表及索引)。這適用於分開管理 schema 和索引,而且執行階段資料庫角色沒有 DDL 權限的 CI/CD 流程。亦可透過 MASTRA\_DISABLE\_STORAGE\_INIT 環境變數啟用。 (Default: `false`) ## 建構函數範例 ### 連線字串 ```ts import { PgVector } from '@mastra/pg' const vectorStore = new PgVector({ id: 'pg-vector', connectionString: 'postgresql://user:password@localhost:5432/mydb', }) ``` ### 主機/連接埠/資料庫配置 ```ts const vectorStore = new PgVector({ id: 'pg-vector', host: 'localhost', port: 5432, database: 'mydb', user: 'postgres', password: 'password', }) ``` ### 進階配置 ```ts const vectorStore = new PgVector({ id: 'pg-vector', connectionString: 'postgresql://user:password@localhost:5432/mydb', schemaName: 'custom_schema', max: 30, idleTimeoutMillis: 60000, pgPoolOptions: { connectionTimeoutMillis: 5000, allowExitOnIdle: true, }, }) ``` ## 方法 ### `createIndex()` **indexName** (`string`): 要建立的索引名稱 **dimension** (`number`): 向量維度(必須與你的嵌入模型相符) **metric** (`'cosine' | 'euclidean' | 'dotproduct'`): 相似度搜尋的距離度量 (Default: `cosine`) **indexConfig** (`IndexConfig`): 索引配置 (Default: `{ type: 'ivfflat' }`) **buildIndex** (`boolean`): 是否建立索引 (Default: `true`) **metadataIndexes** (`string[]`): 要建立 btree 索引的 metadata 欄位名稱陣列。按這些 metadata 欄位篩選時,可改善查詢效能。 #### `IndexConfig` **type** (`'flat' | 'hnsw' | 'ivfflat'`): 索引類型 (Default: `ivfflat`) **type.flat** (`flat`): 執行窮舉搜尋的循序掃描(不使用索引)。 **type.ivfflat** (`ivfflat`): 將向量分群為多個清單,以進行近似搜尋。 **type.hnsw** (`hnsw`): 以圖形為基礎的索引,提供快速搜尋和高召回率。 **ivf** (`IVFConfig`): IVF 配置 **ivf.lists** (`number`): 清單數目。如未指定,會根據資料集大小自動計算。(最少 100,最多 4000) **hnsw** (`HNSWConfig`): HNSW 配置 **hnsw\.m** (`number`): 每個節點的連線數目上限(預設:8) **hnsw\.efConstruction** (`number`): 建立時複雜度(預設:32) #### 記憶體需求 建立 HNSW 索引時需要大量共享記憶體。以 10 萬個向量為例: - 小維度(64d):使用預設設定時約為 \~60MB - 中等維度(256d):使用預設設定時約為 \~180MB - 大維度(384d+):使用預設設定時約為 \~250MB+ 較高的 M 或 efConstruction 值會大幅增加記憶體需求。如有需要,請調整系統的共享記憶體上限。 ### `upsert()` **indexName** (`string`): 要向其中 upsert 向量的索引名稱 **vectors** (`number[][]`): 嵌入向量陣列 **metadata** (`Record[]`): 每個向量的 metadata **ids** (`string[]`): 可選的向量 ID(如未提供則自動產生) ### `query()` **indexName** (`string`): 要查詢的索引名稱 **queryVector** (`number[]`): 查詢向量 **topK** (`number`): 要傳回的結果數目 (Default: `10`) **filter** (`Record`): Metadata 篩選條件 **includeVector** (`boolean`): 結果是否包含向量 (Default: `false`) **minScore** (`number`): 最低相似度分數門檻 (Default: `0`) **options** (`{ ef?: number; probes?: number }`): HNSW 和 IVF 索引的其他選項 **options.ef** (`number`): HNSW 搜尋參數 **options.probes** (`number`): IVF 搜尋參數 ### `listIndexes()` 傳回由索引名稱字串組成的陣列。 ### `describeIndex()` **indexName** (`string`): 要描述的索引名稱 傳回: ```typescript interface PGIndexStats { dimension: number count: number metric: 'cosine' | 'euclidean' | 'dotproduct' type: 'flat' | 'hnsw' | 'ivfflat' config: { m?: number efConstruction?: number lists?: number probes?: number } } ``` ### `deleteIndex()` **indexName** (`string`): 要刪除的索引名稱 ### `updateVector()` 按 ID 或 metadata 篩選條件更新單一向量。必須提供 `id` 或 `filter`,但不可同時提供兩者。 **indexName** (`string`): 包含該向量的索引名稱 **id** (`string`): 要更新的向量 ID(與 filter 互斥) **filter** (`Record`): 用於識別要更新向量的 metadata 篩選條件(與 id 互斥) **update** (`{ vector?: number[]; metadata?: Record; }`): 包含要更新向量及/或 metadata 的物件 按 ID 或篩選條件更新現有向量。update 物件中必須提供 vector 或 metadata,至少提供其中一項。 ```typescript // Update by ID await pgVector.updateVector({ indexName: 'my_vectors', id: 'vector123', update: { vector: [0.1, 0.2, 0.3], metadata: { label: 'updated' }, }, }) // Update by filter await pgVector.updateVector({ indexName: 'my_vectors', filter: { category: 'product' }, update: { metadata: { status: 'reviewed' }, }, }) ``` ### `deleteVector()` **indexName** (`string`): 包含該向量的索引名稱 **id** (`string`): 要刪除的向量 ID 從指定索引按 ID 刪除單一向量。 ```typescript await pgVector.deleteVector({ indexName: 'my_vectors', id: 'vector123' }) ``` ### `deleteVectors()` 按 ID 或 metadata 篩選條件刪除多個向量。必須提供 `ids` 或 `filter`,但不可同時提供兩者。 **indexName** (`string`): 包含要刪除向量的索引名稱 **ids** (`string[]`): 要刪除的向量 ID 陣列(與 filter 互斥) **filter** (`Record`): 用於識別要刪除向量的 metadata 篩選條件(與 ids 互斥) ### `disconnect()` 關閉資料庫連線池。使用完儲存後應呼叫此方法。 ### `buildIndex()` **indexName** (`string`): 要定義的索引名稱 **metric** (`'cosine' | 'euclidean' | 'dotproduct'`): 相似度搜尋的距離度量 (Default: `cosine`) **indexConfig** (`IndexConfig`): 索引類型和參數的配置 使用指定的度量和配置建立或重建索引。建立新索引前會移除任何現有索引。 ```typescript // Define HNSW index await pgVector.buildIndex('my_vectors', 'cosine', { type: 'hnsw', hnsw: { m: 8, efConstruction: 32, }, }) // Define IVF index await pgVector.buildIndex('my_vectors', 'cosine', { type: 'ivfflat', ivf: { lists: 100, }, }) // Define flat index await pgVector.buildIndex('my_vectors', 'cosine', { type: 'flat', }) ``` ## 回應類型 查詢結果會以以下格式傳回: ```typescript interface QueryResult { id: string score: number metadata: Record vector?: number[] // Only included if includeVector is true } ``` ## 錯誤處理 儲存會拋出可捕捉的具型別錯誤: ```typescript try { await store.query({ indexName: 'index_name', queryVector: queryVector, }) } catch (error) { if (error instanceof VectorStoreError) { console.log(error.code) // 'connection_failed' | 'invalid_dimension' | etc console.log(error.details) // Additional error context } } ``` ## 索引配置指南 ### 效能最佳化 #### IVFFlat 調整 - **lists 參數**:設為 `sqrt(n) * 2`,其中 n 是向量數目 - 清單越多,準確度越高,但建立時間越長 - 清單越少,建立速度越快,但準確度可能較低 #### HNSW 調整 - **m 參數**: - 8-16:中等準確度,較低記憶體用量 - 16-32:高準確度,中等記憶體用量 - 32-64:極高準確度,高記憶體用量 - **efConstruction**: - 32-64:建立速度快,品質良好 - 64-128:建立速度較慢,品質較佳 - 128-256:建立速度最慢,品質最佳 ### 索引重建行為 系統會自動偵測配置變更,並只在有需要時重建索引: - 配置相同:保留索引(不會重建) - 配置已變更:移除並重建索引 - 這可避免不必要的索引重建所造成的效能問題 ## 最佳做法 - 定期評估索引配置,確保效能最佳。 - 根據資料集大小及查詢需求調整 `lists` 和 `m` 等參數。 - 使用 `describeIndex()` **監察索引效能**,追蹤使用情況 - 定期重建索引以維持效率,尤其是在資料大幅變更後 ## 直接存取連線池 `PgVector` 類別會將底層 PostgreSQL 連線池公開為 public 欄位: ```typescript pgVector.pool // instance of pg.Pool ``` 這讓你可以執行直接 SQL 查詢、管理交易或監察連線池狀態等進階操作。直接使用連線池時: - 你有責任在用完後釋放 client(`client.release()`)。 - 呼叫 `disconnect()` 後仍可存取連線池,但新的查詢會失敗。 - 直接存取會繞過 PgVector 方法提供的任何驗證或交易邏輯。 這項設計支援進階使用情境,但使用者必須小心管理資源。 ## 使用範例 ### 使用 fastembed 的本機嵌入 嵌入是 memory 的 `semanticRecall` 用來按語意(而非關鍵字)擷取相關訊息的數值向量。此設定使用 `@mastra/fastembed` 產生向量嵌入。 安裝 `fastembed` 以開始使用: **npm**: ```bash npm install @mastra/fastembed@latest ``` **pnpm**: ```bash pnpm add @mastra/fastembed@latest ``` **Yarn**: ```bash yarn add @mastra/fastembed@latest ``` **Bun**: ```bash bun add @mastra/fastembed@latest ``` 將以下內容加入你的 Agent: ```typescript import { Memory } from '@mastra/memory' import { Agent } from '@mastra/core/agent' import { PostgresStore, PgVector } from '@mastra/pg' import { fastembed } from '@mastra/fastembed' export const pgAgent = new Agent({ id: 'pg-agent', name: 'PG Agent', instructions: 'You are an AI agent with the ability to automatically recall memories from previous interactions.', model: 'openai/gpt-5.6-sol', memory: new Memory({ storage: new PostgresStore({ id: 'pg-agent-storage', connectionString: process.env.DATABASE_URL!, }), vector: new PgVector({ id: 'pg-agent-vector', connectionString: process.env.DATABASE_URL!, }), embedder: fastembed, options: { lastMessages: 10, semanticRecall: { topK: 3, messageRange: 2, }, }, }), }) ``` ## 相關內容 - [Metadata 篩選條件](https://mastra.zisheng.pro/zh-HK/reference/rag/metadata-filters)