跳到主要内容

PG Vector 存储

PgVector 类使用 PostgreSQL 及其 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
= false
设为 true 时,将跳过 createIndex 中的自动 DDL(schema、扩展、表和索引创建)。适用于 schema 和索引由单独流程管理,且运行时数据库角色没有 DDL 权限的 CI/CD 流水线。也可以通过 MASTRA_DISABLE_STORAGE_INIT 环境变量启用。

构造函数示例
构造函数示例的直接链接

连接字符串
连接字符串的直接链接

import { PgVector } from '@mastra/pg'

const vectorStore = new PgVector({
id: 'pg-vector',
connectionString: 'postgresql://user:password@localhost:5432/mydb',
})

主机/端口/数据库配置
主机/端口/数据库配置的直接链接

const vectorStore = new PgVector({
id: 'pg-vector',
host: 'localhost',
port: 5432,
database: 'mydb',
user: 'postgres',
password: 'password',
})

高级配置
高级配置的直接链接

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()
createindex的直接链接

indexName:

string
要创建的索引名称

dimension:

number
Vector 维度(必须与嵌入模型匹配)

metric?:

'cosine' | 'euclidean' | 'dotproduct'
= cosine
相似度搜索使用的距离度量

indexConfig?:

IndexConfig
= { type: 'ivfflat' }
索引配置

buildIndex?:

boolean
= true
是否构建索引

metadataIndexes?:

string[]
要创建 btree 索引的元数据字段名称数组。按这些元数据字段筛选时,可提升查询性能。

IndexConfig
indexconfig的直接链接

type:

'flat' | 'hnsw' | 'ivfflat'
= ivfflat
索引类型
string

flat:

flat
执行穷举搜索的顺序扫描(无索引)。

ivfflat:

ivfflat
将 Vector 聚类到列表中以进行近似搜索。

hnsw:

hnsw
基于图的索引,可提供快速搜索和高召回率。

ivf?:

IVFConfig
IVF 配置
object

lists?:

number
列表数量。未指定时,将根据数据集大小自动计算。(最小值 100,最大值 4000)

hnsw?:

HNSWConfig
HNSW 配置
object

m?:

number
每个节点的最大连接数(默认值:8)

efConstruction?:

number
构建时复杂度(默认值:32)

内存要求
内存要求的直接链接

HNSW 索引在构建期间需要大量共享内存。对于 10 万个 Vector:

  • 小维度(64d):默认设置下约为 ~60MB
  • 中等维度(256d):默认设置下约为 ~180MB
  • 大维度(384d+):默认设置下约为 ~250MB+

增大 M 或 efConstruction 值会大幅提高内存要求。必要时请调整系统的共享内存限制。

upsert()
upsert的直接链接

indexName:

string
要 upsert Vector 的索引名称

vectors:

number[][]
嵌入 Vector 数组

metadata?:

Record<string, any>[]
每个 Vector 的元数据

ids?:

string[]
可选的 Vector ID(未提供时自动生成)

query()
query的直接链接

indexName:

string
要查询的索引名称

queryVector:

number[]
查询 Vector

topK?:

number
= 10
要返回的结果数量

filter?:

Record<string, any>
元数据筛选条件

includeVector?:

boolean
= false
结果中是否包含 Vector

minScore?:

number
= 0
最低相似度分数阈值

options?:

{ ef?: number; probes?: number }
HNSW 和 IVF 索引的其他选项
object

ef?:

number
HNSW 搜索参数

probes?:

number
IVF 搜索参数

listIndexes()
listindexes的直接链接

返回由索引名称字符串组成的数组。

describeIndex()
describeindex的直接链接

indexName:

string
要描述的索引名称

返回:

interface PGIndexStats {
dimension: number
count: number
metric: 'cosine' | 'euclidean' | 'dotproduct'
type: 'flat' | 'hnsw' | 'ivfflat'
config: {
m?: number
efConstruction?: number
lists?: number
probes?: number
}
}

deleteIndex()
deleteindex的直接链接

indexName:

string
要删除的索引名称

updateVector()
updatevector的直接链接

按 ID 或元数据筛选条件更新单个 Vector。必须提供 idfilter,但不能同时提供两者。

indexName:

string
包含待更新 Vector 的索引名称

id?:

string
要更新的 Vector ID(不能与 filter 同时使用)

filter?:

Record<string, any>
用于标识待更新 Vector 的元数据筛选条件(不能与 id 同时使用)

update:

{ vector?: number[]; metadata?: Record<string, any>; }
包含待更新 Vector 和/或元数据的对象

按 ID 或筛选条件更新现有 Vector。update 对象必须至少提供 vector 或 metadata 中的一个。

// 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()
deletevector的直接链接

indexName:

string
包含待删除 Vector 的索引名称

id:

string
要删除的 Vector ID

按 ID 从指定索引中删除单个 Vector。

await pgVector.deleteVector({ indexName: 'my_vectors', id: 'vector123' })

deleteVectors()
deletevectors的直接链接

按 ID 或元数据筛选条件删除多个 Vector。必须提供 idsfilter,但不能同时提供两者。

indexName:

string
包含待删除 Vector 的索引名称

ids?:

string[]
要删除的 Vector ID 数组(不能与 filter 同时使用)

filter?:

Record<string, any>
用于标识待删除 Vector 的元数据筛选条件(不能与 ids 同时使用)

disconnect()
disconnect的直接链接

关闭数据库连接池。使用完存储后应调用此方法。

buildIndex()
buildindex的直接链接

indexName:

string
要定义的索引名称

metric?:

'cosine' | 'euclidean' | 'dotproduct'
= cosine
相似度搜索使用的距离度量

indexConfig:

IndexConfig
索引类型和参数的配置

使用指定的度量和配置构建或重新构建索引。创建新索引前会删除所有现有索引。

// 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',
})

响应类型
响应类型的直接链接

查询结果以以下格式返回:

interface QueryResult {
id: string
score: number
metadata: Record<string, any>
vector?: number[] // Only included if includeVector is true
}

错误处理
错误处理的直接链接

存储会抛出可捕获的类型化错误:

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 调优
IVFFlat 调优的直接链接

  • lists 参数:设置为 sqrt(n) * 2,其中 n 是 Vector 数量
  • 列表越多,准确率越高,但构建时间越长
  • 列表越少,构建速度越快,但准确率可能越低

HNSW 调优
HNSW 调优的直接链接

  • m 参数
    • 8-16:中等准确率,较低内存占用
    • 16-32:高准确率,中等内存占用
    • 32-64:极高准确率,高内存占用
  • efConstruction
    • 32-64:构建快,质量良好
    • 64-128:构建较慢,质量更好
    • 128-256:构建最慢,质量最佳

索引重建行为
索引重建行为的直接链接

系统会自动检测配置更改,仅在必要时重建索引:

  • 配置相同:保留索引(不重建)
  • 配置已更改:删除并重建索引
  • 这可以避免不必要的索引重建导致性能问题

最佳实践
最佳实践的直接链接

  • 定期评估索引配置,确保获得最佳性能。
  • 根据数据集大小和查询要求调整 listsm 等参数。
  • 使用 describeIndex() 监控索引性能,以跟踪使用情况
  • 定期重建索引以保持效率,尤其是在数据发生大量更改后

直接访问连接池
直接访问连接池的直接链接

PgVector 类将其底层 PostgreSQL 连接池公开为公共字段:

pgVector.pool // instance of pg.Pool

这支持直接运行 SQL 查询、管理事务或监控连接池状态等高级用法。直接使用连接池时:

  • 需要负责在使用后释放客户端(client.release())。
  • 调用 disconnect() 后仍可访问连接池,但新查询将失败。
  • 直接访问会绕过 PgVector 方法提供的所有验证或事务逻辑。

此设计支持高级用例,但要求用户谨慎管理资源。

用法示例
用法示例的直接链接

使用 fastembed 的本地嵌入
使用 fastembed 的本地嵌入的直接链接

嵌入是数字 Vector,memory 的 semanticRecall 使用它按含义(而不是关键词)检索相关消息。此设置使用 @mastra/fastembed 生成 Vector embedding。

安装 fastembed 以开始使用:

npm install @mastra/fastembed@latest

将以下内容添加到 Agent:

src/mastra/agents/example-pg-agent.ts
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,
},
},
}),
})