PG vector store
The PgVector class provides vector search using PostgreSQL with pgvector extension. It provides reliable vector similarity search capabilities within your existing PostgreSQL database.
Constructor optionsConstructor options的直接链接
connectionString?:
host?:
port?:
database?:
user?:
password?:
ssl?:
schemaName?:
max?:
idleTimeoutMillis?:
pgPoolOptions?:
disableInit?:
createIndex is skipped. Useful for CI/CD pipelines where schema and indexes are managed separately and the runtime database role lacks DDL privileges. Can also be enabled with the MASTRA_DISABLE_STORAGE_INIT environment variable.Constructor examplesConstructor examples的直接链接
Connection StringConnection String的直接链接
import { PgVector } from '@mastra/pg'
const vectorStore = new PgVector({
id: 'pg-vector',
connectionString: 'postgresql://user:password@localhost:5432/mydb',
})
Host/Port/Database ConfigurationHost/Port/Database Configuration的直接链接
const vectorStore = new PgVector({
id: 'pg-vector',
host: 'localhost',
port: 5432,
database: 'mydb',
user: 'postgres',
password: 'password',
})
Advanced ConfigurationAdvanced Configuration的直接链接
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,
},
})
MethodsMethods的直接链接
createIndex()createindex的直接链接
indexName:
dimension:
metric?:
vectorType?:
indexConfig?:
buildIndex?:
metadataIndexes?:
IndexConfigindexconfig的直接链接
type:
flat:
ivfflat:
hnsw:
ivf?:
lists?:
hnsw?:
m?:
efConstruction?:
Memory RequirementsMemory Requirements的直接链接
HNSW indexes require substantial shared memory during construction. For 100K vectors:
- Small dimensions (64d): ~60MB with default settings
- Medium dimensions (256d): ~180MB with default settings
- Large dimensions (384d+): ~250MB+ with default settings
Higher M values or efConstruction values will increase memory requirements substantially. Adjust your system's shared memory limits if needed.
upsert()upsert的直接链接
indexName:
vectors:
metadata?:
ids?:
query()query的直接链接
indexName:
queryVector:
topK?:
filter?:
includeVector?:
minScore?:
ef?:
probes?:
listIndexes()listindexes的直接链接
Returns an array of index names as strings.
describeIndex()describeindex的直接链接
indexName:
Returns:
interface PGIndexStats {
dimension: number
count: number
metric: 'cosine' | 'euclidean' | 'dotproduct' | 'hamming' | 'jaccard'
type: 'flat' | 'hnsw' | 'ivfflat'
vectorType: 'vector' | 'halfvec' | 'bit' | 'sparsevec'
config: {
m?: number
efConstruction?: number
lists?: number
probes?: number
}
}
count is an exact SELECT COUNT(*), which scans the whole table, so avoid calling describeIndex() on a hot path for a large index. Reads and writes never pay for it: they only use the index metadata, which comes from the Postgres catalog.
deleteIndex()deleteindex的直接链接
indexName:
updateVector()updatevector的直接链接
Update a single vector by ID or by metadata filter. Either id or filter must be provided, but not both.
indexName:
id?:
filter?:
update:
Updates an existing vector by ID or filter. At least one of vector or metadata must be provided in the update object.
// 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:
id:
Deletes a single vector by ID from the specified index.
await pgVector.deleteVector({ indexName: 'my_vectors', id: 'vector123' })
deleteVectors()deletevectors的直接链接
Delete multiple vectors by IDs or by metadata filter. Either ids or filter must be provided, but not both.
indexName:
ids?:
filter?:
disconnect()disconnect的直接链接
Closes the database connection pool. Should be called when done using the store.
buildIndex()buildindex的直接链接
indexName:
metric?:
indexConfig:
Builds or rebuilds an index with specified metric and configuration. Will drop any existing index before creating the new one.
// 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',
})
Response typesResponse types的直接链接
Query results are returned in this format:
interface QueryResult {
id: string
score: number
metadata: Record<string, any>
vector?: number[] // Only included if includeVector is true
}
Error handlingError handling的直接链接
The store throws MastraError instances from @mastra/core/error:
import { MastraError } from '@mastra/core/error'
try {
await store.query({
indexName: 'index_name',
queryVector: queryVector,
})
} catch (error) {
if (error instanceof MastraError) {
console.log(error.id) // 'MASTRA_VECTOR_PG_QUERY_FAILED'
console.log(error.domain) // 'MASTRA_VECTOR'
console.log(error.category) // 'USER' | 'THIRD_PARTY'
console.log(error.details) // Additional error context
}
}
Index configuration guideIndex configuration guide的直接链接
Performance OptimizationPerformance Optimization的直接链接
IVFFlat TuningIVFFlat Tuning的直接链接
- lists parameter: Set to
sqrt(n) * 2where n is the number of vectors - More lists = better accuracy but slower build time
- Fewer lists = faster build but potentially lower accuracy
HNSW TuningHNSW Tuning的直接链接
- m parameter:
- 8-16: Moderate accuracy, lower memory
- 16-32: High accuracy, moderate memory
- 32-64: Very high accuracy, high memory
- efConstruction:
- 32-64: Fast build, good quality
- 64-128: Slower build, better quality
- 128-256: Slowest build, best quality
Index Recreation BehaviorIndex Recreation Behavior的直接链接
The system automatically detects configuration changes and only rebuilds indexes when necessary:
- Same configuration: Index is kept (no recreation)
- Changed configuration: Index is dropped and rebuilt
- This prevents the performance issues from unnecessary index recreations
Best practicesBest practices的直接链接
- Regularly evaluate your index configuration to ensure optimal performance.
- Adjust parameters like
listsandmbased on dataset size and query requirements. - Monitor index performance using
describeIndex()to track usage - Rebuild indexes periodically to maintain efficiency, especially after substantial data changes
Direct pool accessDirect pool access的直接链接
The PgVector class exposes its underlying PostgreSQL connection pool as a public field:
pgVector.pool // instance of pg.Pool
Direct pool access supports advanced operations such as direct SQL queries, transactions, or pool-state monitoring. When using the pool directly:
- You are responsible for releasing clients (
client.release()) after use. - The pool remains accessible after calling
disconnect(), but new queries will fail. - Direct access bypasses any validation or transaction logic provided by PgVector methods.
This design supports advanced use cases but requires careful resource management by the user.
Usage exampleUsage example的直接链接
Local embeddings with fastembedLocal embeddings with fastembed的直接链接
Embeddings are numeric vectors used by memory's semanticRecall to retrieve related messages by meaning (not keywords). This setup uses @mastra/fastembed to generate vector embeddings.
Install fastembed to get started:
- npm
- pnpm
- Yarn
- Bun
npm install @mastra/fastembed@latest
pnpm add @mastra/fastembed@latest
yarn add @mastra/fastembed@latest
bun add @mastra/fastembed@latest
Add the following to your agent:
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,
},
},
}),
})