> Discover all available pages from the documentation index: https://mastra.zisheng.pro/llms.txt # PG Vector 存储 PgVector 类使用 [PostgreSQL](https://www.postgresql.org/) 及其 [pgvector](https://github.com/pgvector/pgvector) 扩展提供 Vector 搜索。 它可在现有 PostgreSQL 数据库中提供可靠的 Vector 相似度搜索功能。 ## 构造函数选项 **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`): Vector 存储要使用的 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`): Vector 维度(必须与嵌入模型匹配) **metric** (`'cosine' | 'euclidean' | 'dotproduct'`): 相似度搜索使用的距离度量 (Default: `cosine`) **indexConfig** (`IndexConfig`): 索引配置 (Default: `{ type: 'ivfflat' }`) **buildIndex** (`boolean`): 是否构建索引 (Default: `true`) **metadataIndexes** (`string[]`): 要创建 btree 索引的元数据字段名称数组。按这些元数据字段筛选时,可提升查询性能。 #### `IndexConfig` **type** (`'flat' | 'hnsw' | 'ivfflat'`): 索引类型 (Default: `ivfflat`) **type.flat** (`flat`): 执行穷举搜索的顺序扫描(无索引)。 **type.ivfflat** (`ivfflat`): 将 Vector 聚类到列表中以进行近似搜索。 **type.hnsw** (`hnsw`): 基于图的索引,可提供快速搜索和高召回率。 **ivf** (`IVFConfig`): IVF 配置 **ivf.lists** (`number`): 列表数量。未指定时,将根据数据集大小自动计算。(最小值 100,最大值 4000) **hnsw** (`HNSWConfig`): HNSW 配置 **hnsw\.m** (`number`): 每个节点的最大连接数(默认值:8) **hnsw\.efConstruction** (`number`): 构建时复杂度(默认值:32) #### 内存要求 HNSW 索引在构建期间需要大量共享内存。对于 10 万个 Vector: - 小维度(64d):默认设置下约为 \~60MB - 中等维度(256d):默认设置下约为 \~180MB - 大维度(384d+):默认设置下约为 \~250MB+ 增大 M 或 efConstruction 值会大幅提高内存要求。必要时请调整系统的共享内存限制。 ### `upsert()` **indexName** (`string`): 要 upsert Vector 的索引名称 **vectors** (`number[][]`): 嵌入 Vector 数组 **metadata** (`Record[]`): 每个 Vector 的元数据 **ids** (`string[]`): 可选的 Vector ID(未提供时自动生成) ### `query()` **indexName** (`string`): 要查询的索引名称 **queryVector** (`number[]`): 查询 Vector **topK** (`number`): 要返回的结果数量 (Default: `10`) **filter** (`Record`): 元数据筛选条件 **includeVector** (`boolean`): 结果中是否包含 Vector (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 或元数据筛选条件更新单个 Vector。必须提供 `id` 或 `filter`,但不能同时提供两者。 **indexName** (`string`): 包含待更新 Vector 的索引名称 **id** (`string`): 要更新的 Vector ID(不能与 filter 同时使用) **filter** (`Record`): 用于标识待更新 Vector 的元数据筛选条件(不能与 id 同时使用) **update** (`{ vector?: number[]; metadata?: Record; }`): 包含待更新 Vector 和/或元数据的对象 按 ID 或筛选条件更新现有 Vector。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`): 包含待删除 Vector 的索引名称 **id** (`string`): 要删除的 Vector ID 按 ID 从指定索引中删除单个 Vector。 ```typescript await pgVector.deleteVector({ indexName: 'my_vectors', id: 'vector123' }) ``` ### `deleteVectors()` 按 ID 或元数据筛选条件删除多个 Vector。必须提供 `ids` 或 `filter`,但不能同时提供两者。 **indexName** (`string`): 包含待删除 Vector 的索引名称 **ids** (`string[]`): 要删除的 Vector ID 数组(不能与 filter 同时使用) **filter** (`Record`): 用于标识待删除 Vector 的元数据筛选条件(不能与 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 是 Vector 数量 - 列表越多,准确率越高,但构建时间越长 - 列表越少,构建速度越快,但准确率可能越低 #### HNSW 调优 - **m 参数**: - 8-16:中等准确率,较低内存占用 - 16-32:高准确率,中等内存占用 - 32-64:极高准确率,高内存占用 - **efConstruction**: - 32-64:构建快,质量良好 - 64-128:构建较慢,质量更好 - 128-256:构建最慢,质量最佳 ### 索引重建行为 系统会自动检测配置更改,仅在必要时重建索引: - 配置相同:保留索引(不重建) - 配置已更改:删除并重建索引 - 这可以避免不必要的索引重建导致性能问题 ## 最佳实践 - 定期评估索引配置,确保获得最佳性能。 - 根据数据集大小和查询要求调整 `lists` 和 `m` 等参数。 - 使用 `describeIndex()` **监控索引性能**,以跟踪使用情况 - 定期重建索引以保持效率,尤其是在数据发生大量更改后 ## 直接访问连接池 `PgVector` 类将其底层 PostgreSQL 连接池公开为公共字段: ```typescript pgVector.pool // instance of pg.Pool ``` 这支持直接运行 SQL 查询、管理事务或监控连接池状态等高级用法。直接使用连接池时: - 需要负责在使用后释放客户端(`client.release()`)。 - 调用 `disconnect()` 后仍可访问连接池,但新查询将失败。 - 直接访问会绕过 PgVector 方法提供的所有验证或事务逻辑。 此设计支持高级用例,但要求用户谨慎管理资源。 ## 用法示例 ### 使用 fastembed 的本地嵌入 嵌入是数字 Vector,memory 的 `semanticRecall` 使用它按含义(而不是关键词)检索相关消息。此设置使用 `@mastra/fastembed` 生成 Vector embedding。 安装 `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, }, }, }), }) ``` ## 相关内容 - [元数据筛选器](https://mastra.zisheng.pro/reference/rag/metadata-filters)