Aurora DSQL 儲存空間
Aurora DSQL 儲存空間實作採用具備 IAM 驗證的 Amazon Aurora DSQL 提供儲存空間。
Aurora DSQL 不支援 PostgreSQL extension(CREATE EXTENSION),包括 pgvector。向量儲存請使用 @mastra/s3vectors 等獨立向量 store。
安裝「安裝」的直接連結
npm install @mastra/dsql@beta
先決條件「先決條件」的直接連結
- Amazon Aurora DSQL cluster
- 具備 DSQL cluster 存取權的 AWS credential(IAM 驗證)
使用方式「使用方式」的直接連結
import { DSQLStore } from '@mastra/dsql'
const storage = new DSQLStore({
id: 'my-dsql-store',
host: 'abc123.dsql.us-east-1.on.aws',
// region is auto-detected from host, or specify explicitly:
// region: 'us-east-1',
// user: 'admin', // default
// database: 'postgres', // default
})
// Initialize the store (creates tables if needed)
await storage.init()
參數「參數」的直接連結
id:
host:
pool?:
user?:
database?:
region?:
schemaName?:
customCredentialsProvider?:
max?:
min?:
idleTimeoutMillis?:
maxLifetimeSeconds?:
connectionTimeoutMillis?:
allowExitOnIdle?:
建構函式範例「建構函式範例」的直接連結
你可以使用下列方式建立 DSQLStore 執行個體:
import { DSQLStore } from '@mastra/dsql'
// Basic configuration (region auto-detected from host)
const store1 = new DSQLStore({
id: 'my-dsql-store',
host: 'abc123.dsql.us-east-1.on.aws',
})
// With explicit region and schema
const store2 = new DSQLStore({
id: 'my-dsql-store',
host: 'abc123.dsql.us-east-1.on.aws',
region: 'us-east-1',
schemaName: 'my_app',
})
// With custom credentials provider
import { fromNodeProviderChain } from '@aws-sdk/credential-providers'
const store3 = new DSQLStore({
id: 'my-dsql-store',
host: 'abc123.dsql.us-east-1.on.aws',
customCredentialsProvider: fromNodeProviderChain(),
})
// With connection pool settings
const store4 = new DSQLStore({
id: 'my-dsql-store',
host: 'abc123.dsql.us-east-1.on.aws',
max: 20,
min: 2,
idleTimeoutMillis: 300000,
maxLifetimeSeconds: 3000,
connectionTimeoutMillis: 10000,
})
// Using a pre-configured pg.Pool
import { Pool } from 'pg'
import { AuroraDSQLClient } from '@aws/aurora-dsql-node-postgres-connector'
const pool = new Pool({
host: 'abc123.dsql.us-east-1.on.aws',
Client: AuroraDSQLClient,
region: 'us-east-1',
})
const store5 = new DSQLStore({
id: 'my-dsql-store',
pool,
})
其他注意事項「其他注意事項」的直接連結
Schema 管理「Schema 管理」的直接連結
儲存空間實作會自動處理 schema 的建立與更新,並建立下列資料表:
mastra_workflow_snapshot:儲存 Workflow 狀態與執行資料mastra_threads:儲存對話 threadmastra_messages:儲存個別訊息mastra_ai_spans:儲存用於可觀測性的 span 資料mastra_scorers:儲存評分與評估資料mastra_resources:儲存資源的 working memory 資料mastra_agents:儲存 Agent 資料
初始化「初始化」的直接連結
將 storage 傳入 Mastra 類別時,系統會在進行任何儲存操作前自動呼叫 init():
import { Mastra } from '@mastra/core'
import { DSQLStore } from '@mastra/dsql'
const storage = new DSQLStore({
id: 'my-dsql-store',
host: 'abc123.dsql.us-east-1.on.aws',
})
const mastra = new Mastra({
storage, // init() is called automatically
})
若不透過 Mastra 而直接使用 storage,必須明確呼叫 init() 來建立資料表:
import { DSQLStore } from '@mastra/dsql'
const storage = new DSQLStore({
id: 'my-dsql-store',
host: 'abc123.dsql.us-east-1.on.aws',
})
// Required when using storage directly
await storage.init()
// Access domain-specific stores via getStore()
const memoryStore = await storage.getStore('memory')
const thread = await memoryStore?.getThreadById({ threadId: '...' })
若未呼叫 init(),系統不會建立資料表,儲存操作將會無聲失敗或擲回錯誤。
直接存取資料庫與連線池「直接存取資料庫與連線池」的直接連結
DSQLStore 會以公開欄位提供底層資料庫 client 與 pg.Pool 執行個體:
storage.db // Database client for executing queries
storage.pool // Underlying pg.Pool instance
它支援直接查詢與自訂交易管理。使用這些欄位時:
- 你必須負責正確處理連線與交易。
- 若連線池是由 store 建立,關閉 store(
storage.close())時會銷毀連線池。 - 直接存取會略過 DSQLStore 方法提供的任何額外邏輯或驗證。
此方式適用於需要低階存取的進階情境。
Aurora DSQL 特性「Aurora DSQL 特性」的直接連結
僅限 IAM 驗證「僅限 IAM 驗證」的直接連結
連線使用 IAM 驗證,不需要資料庫密碼。@mastra/dsql 使用 @aws/aurora-dsql-node-postgres-connector 產生短期 auth token。你可以透過 customCredentialsProvider 提供自訂 credential Provider。
單一資料庫、以 schema 為基礎的隔離「單一資料庫、以 schema 為基礎的隔離」的直接連結
每個 cluster 都只提供一個 postgres 資料庫。邏輯隔離透過 schema 完成。schemaName 選項控制 Mastra 資料表的建立位置。
不支援 PostgreSQL extension「不支援 PostgreSQL extension」的直接連結
系統不支援 CREATE EXTENSION,包括 pgvector、PostGIS 等。向量儲存請搭配 DSQLStore 使用 @mastra/s3vectors 等獨立 store。
以文字儲存 JSON「以文字儲存 JSON」的直接連結
JSON/JSONB 可作為查詢型別,但不能作為欄位型別。@mastra/dsql 會將結構化欄位(metadata、內容等)儲存在 TEXT 欄位中,並在查詢時轉型為 JSON。
Schema 與 DDL 限制「Schema 與 DDL 限制」的直接連結
部分 PostgreSQL 功能無法使用:
- Foreign key constraint
TRUNCATE- 同步
CREATE INDEX
索引會使用 CREATE INDEX ASYNC 非同步建立。store 的 init() 與索引 helper API 會遵守這些限制。
交易與樂觀並行控制「交易與樂觀並行控制」的直接連結
Aurora DSQL 使用樂觀並行控制(OCC),發生競爭時可能傳回可重試的 OCC 錯誤。交易持續時間與大小都有上限。大型批次操作應在應用程式層級拆分為較小批次。
連線存續時間「連線存續時間」的直接連結
單一連線限制約為 60 分鐘。預設的 maxLifetimeSeconds: 3300 可確保連線在達到限制前回收。
使用範例「使用範例」的直接連結
為 Agent 新增記憶體「為 Agent 新增記憶體」的直接連結
若要為 Agent 新增 Aurora DSQL 記憶體,請使用 Memory 類別,並以 DSQLStore 建立新的 storage key。host 應指向 Aurora DSQL cluster endpoint。
import { Memory } from '@mastra/memory'
import { Agent } from '@mastra/core/agent'
import { DSQLStore } from '@mastra/dsql'
export const dsqlAgent = new Agent({
id: 'dsql-agent',
name: 'DSQL 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 DSQLStore({
id: 'dsql-agent-storage',
host: process.env.DSQL_HOST!,
}),
options: {
generateTitle: true, // Explicitly enable automatic title generation
},
}),
})
使用 Agent「使用 Agent」的直接連結
使用 memoryOptions 設定此請求的回憶範圍。設定 lastMessages: 5 以限制依時間順序回憶的訊息數量,並使用 semanticRecall 擷取 topK: 3 筆最相關訊息;其中包含 messageRange: 2 筆相鄰訊息,作為各配對結果的上下文。
import 'dotenv/config'
import { mastra } from './mastra'
const threadId = '123'
const resourceId = 'user-456'
const agent = mastra.getAgent('dsql-agent')
const message = await agent.stream('My name is Mastra', {
memory: {
thread: threadId,
resource: resourceId,
},
})
await message.textStream.pipeTo(new WritableStream())
const stream = await agent.stream("What's my name?", {
memory: {
thread: threadId,
resource: resourceId,
},
memoryOptions: {
lastMessages: 5,
semanticRecall: {
topK: 3,
messageRange: 2,
},
},
})
for await (const chunk of stream.textStream) {
process.stdout.write(chunk)
}
索引管理「索引管理」的直接連結
Aurora DSQL 儲存空間提供索引管理功能,可最佳化查詢效能。
自動效能索引「自動效能索引」的直接連結
Aurora DSQL 儲存空間會在初始化期間,針對常見查詢模式自動建立複合索引:
mastra_threads_resourceid_createdat_idx: (resourceId, createdAt)mastra_messages_thread_id_createdat_idx: (thread_id, createdAt)mastra_ai_spans_traceid_startedat_idx: (traceId, startedAt)mastra_ai_spans_parentspanid_startedat_idx: (parentSpanId, startedAt)mastra_ai_spans_name_idx: (name)mastra_ai_spans_spantype_startedat_idx: (spanType, startedAt)mastra_scores_trace_id_span_id_created_at_idx: (traceId, spanId, createdAt)
Aurora DSQL 使用 CREATE INDEX ASYNC 非同步建立這些索引。由於索引建立作業是非同步的,呼叫 init() 後可能無法立即使用新索引。沒有這些索引時 store 仍可運作,但在索引建立完成前,查詢速度可能較慢。
建立自訂索引「建立自訂索引」的直接連結
建立其他索引以最佳化特定查詢模式:
await storage.createIndex({
name: 'idx_threads_resource',
table: 'mastra_threads',
columns: ['resourceId'],
})
await storage.createIndex({
name: 'idx_messages_composite',
table: 'mastra_messages',
columns: ['thread_id', 'createdAt'],
})
Aurora DSQL 不允許在 CREATE INDEX ASYNC 中使用 ASC/DESC。若包含這些項目,系統會自動移除。
索引選項「索引選項」的直接連結
name:
table:
columns:
unique?:
concurrent?:
where?:
method?:
opclass?:
storage?:
tablespace?:
管理索引「管理索引」的直接連結
列出並監控現有索引:
// List all indexes
const allIndexes = await storage.listIndexes()
console.log(allIndexes)
// [
// {
// name: 'mastra_threads_pkey',
// table: 'mastra_threads',
// columns: ['id'],
// unique: true,
// size: '16 KB',
// definition: 'CREATE UNIQUE INDEX...'
// },
// ...
// ]
// List indexes for a specific table
const threadIndexes = await storage.listIndexes('mastra_threads')
// Get detailed statistics for an index
const stats = await storage.describeIndex('idx_threads_resource')
console.log(stats)
// {
// name: 'idx_threads_resource',
// table: 'mastra_threads',
// columns: ['resourceId'],
// unique: false,
// size: '128 KB',
// definition: 'CREATE INDEX idx_threads_resource...',
// method: 'btree',
// scans: 1542,
// tuples_read: 45230,
// tuples_fetched: 12050
// }
// Drop an index
await storage.dropIndex('idx_threads_status')
Schema 專用索引「Schema 專用索引」的直接連結
使用自訂 schema 時,建立的索引會加上 schema prefix:
const storage = new DSQLStore({
id: 'my-dsql-store',
host: 'abc123.dsql.us-east-1.on.aws',
schemaName: 'custom_schema',
})
// Creates index as: custom_schema_idx_threads_status
await storage.createIndex({
name: 'idx_threads_status',
table: 'mastra_threads',
columns: ['status'],
})