> Discover all available pages from the documentation index: https://mastra.zisheng.pro/zh-TW/llms.txt # Aurora DSQL 儲存空間 Aurora DSQL 儲存空間實作採用具備 IAM 驗證的 Amazon Aurora DSQL 提供儲存空間。 Aurora DSQL 不支援 PostgreSQL extension(`CREATE EXTENSION`),包括 `pgvector`。向量儲存請使用 `@mastra/s3vectors` 等獨立向量 store。 ## 安裝 ```bash npm install @mastra/dsql@beta ``` ## 先決條件 - Amazon Aurora DSQL cluster - 具備 DSQL cluster 存取權的 AWS credential(IAM 驗證) ## 使用方式 ```typescript 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** (`string`): 此 store 執行個體的唯一識別碼 **host** (`string`): DSQL cluster endpoint(例如 abc123.dsql.us-east-1.on.aws) **pool** (`pg.Pool`): 預先設定的 pg.Pool 執行個體。可用於直接控制連線池。無法與 host 設定同時使用。 **user** (`string`): 資料庫使用者。Aurora DSQL 的管理員角色為 'admin'。 **database** (`string`): 資料庫名稱。每個 Aurora DSQL cluster 只提供一個名為 'postgres' 的資料庫。 **region** (`string`): AWS region。若未提供,會從 host 擷取。 **schemaName** (`string`): 建立 Mastra 資料表與索引的 PostgreSQL schema 名稱。 **customCredentialsProvider** (`AwsCredentialIdentityProvider`): 用於 IAM 驗證的自訂 AWS credential Provider。 **max** (`number`): 連線池中的最大連線數。 **min** (`number`): 連線池中的最小連線數。 **idleTimeoutMillis** (`number`): 連線閒置達到此毫秒數後關閉。 **maxLifetimeSeconds** (`number`): 最大連線存續時間(秒)。由於 Aurora DSQL 的連線限制為 60 分鐘,此值必須小於 3600。 **connectionTimeoutMillis** (`number`): 取得連線的逾時時間(毫秒)。 **allowExitOnIdle** (`boolean`): 允許處理程序在所有連線閒置時結束。 ## 建構函式範例 你可以使用下列方式建立 `DSQLStore` 執行個體: ```typescript 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 的建立與更新,並建立下列資料表: - `mastra_workflow_snapshot`:儲存 Workflow 狀態與執行資料 - `mastra_threads`:儲存對話 thread - `mastra_messages`:儲存個別訊息 - `mastra_ai_spans`:儲存用於可觀測性的 span 資料 - `mastra_scorers`:儲存評分與評估資料 - `mastra_resources`:儲存資源的 working memory 資料 - `mastra_agents`:儲存 Agent 資料 ### 初始化 將 storage 傳入 Mastra 類別時,系統會在進行任何儲存操作前自動呼叫 `init()`: ```typescript 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()` 來建立資料表: ```typescript 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 執行個體: ```typescript storage.db // Database client for executing queries storage.pool // Underlying pg.Pool instance ``` 它支援直接查詢與自訂交易管理。使用這些欄位時: - 你必須負責正確處理連線與交易。 - 若連線池是由 store 建立,關閉 store(`storage.close()`)時會銷毀連線池。 - 直接存取會略過 DSQLStore 方法提供的任何額外邏輯或驗證。 此方式適用於需要低階存取的進階情境。 ### Aurora DSQL 特性 #### 僅限 IAM 驗證 連線使用 IAM 驗證,不需要資料庫密碼。`@mastra/dsql` 使用 `@aws/aurora-dsql-node-postgres-connector` 產生短期 auth token。你可以透過 `customCredentialsProvider` 提供自訂 credential Provider。 #### 單一資料庫、以 schema 為基礎的隔離 每個 cluster 都只提供一個 `postgres` 資料庫。邏輯隔離透過 schema 完成。`schemaName` 選項控制 Mastra 資料表的建立位置。 #### 不支援 PostgreSQL extension 系統不支援 `CREATE EXTENSION`,包括 `pgvector`、`PostGIS` 等。向量儲存請搭配 `DSQLStore` 使用 `@mastra/s3vectors` 等獨立 store。 #### 以文字儲存 JSON JSON/JSONB 可作為查詢型別,但不能作為欄位型別。`@mastra/dsql` 會將結構化欄位(metadata、內容等)儲存在 `TEXT` 欄位中,並在查詢時轉型為 JSON。 #### 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 新增 Aurora DSQL 記憶體,請使用 `Memory` 類別,並以 `DSQLStore` 建立新的 `storage` key。`host` 應指向 Aurora DSQL cluster endpoint。 ```typescript 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 使用 `memoryOptions` 設定此請求的回憶範圍。設定 `lastMessages: 5` 以限制依時間順序回憶的訊息數量,並使用 `semanticRecall` 擷取 `topK: 3` 筆最相關訊息;其中包含 `messageRange: 2` 筆相鄰訊息,作為各配對結果的上下文。 ```typescript 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 仍可運作,但在索引建立完成前,查詢速度可能較慢。 ### 建立自訂索引 建立其他索引以最佳化特定查詢模式: ```typescript 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** (`string`): 索引的唯一名稱 **table** (`string`): 資料表名稱(例如 'mastra\_threads') **columns** (`string[]`): 欄位名稱陣列。為了與 Aurora DSQL 相容,系統會自動移除 ASC/DESC modifier。 **unique** (`boolean`): 建立唯一索引。 **concurrent** (`boolean`): Aurora DSQL 會忽略此選項。索引一律以非同步方式建立。 **where** (`string`): 部分索引條件。 **method** (`string`): Aurora DSQL 會忽略此選項。只支援 btree 索引。 **opclass** (`string`): Aurora DSQL 會忽略此選項。 **storage** (`Record`): Aurora DSQL 會忽略此選項。 **tablespace** (`string`): Aurora DSQL 會忽略此選項。 Tablespaces are not supported. ### 管理索引 列出並監控現有索引: ```typescript // 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 prefix: ```typescript 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'], }) ``` ## 相關資源 - [Aurora DSQL 說明文件](https://docs.aws.amazon.com/aurora-dsql/) - [SQL 參考資料](https://docs.aws.amazon.com/aurora-dsql/latest/userguide/working-with-aurora-dsql-sql.html) - [支援的 SQL 功能](https://docs.aws.amazon.com/aurora-dsql/latest/userguide/working-with-postgresql-compatibility-supported-sql-features.html) - [不支援的 PostgreSQL 功能](https://docs.aws.amazon.com/aurora-dsql/latest/userguide/working-with-postgresql-compatibility-unsupported-features.html) - [支援的資料型別](https://docs.aws.amazon.com/aurora-dsql/latest/userguide/working-with-postgresql-compatibility-supported-data-types.html) - [非同步索引](https://docs.aws.amazon.com/aurora-dsql/latest/userguide/working-with-create-index-async.html)