Skip to main content

DynamoDB 存储

🌐 DynamoDB Storage

DynamoDB 存储实现为 Mastra 提供了可扩展且高性能的 NoSQL 数据库解决方案,采用了结合 ElectroDB 的单表设计模式。

🌐 The DynamoDB storage implementation provides a scalable and performant NoSQL database solution for Mastra, leveraging a single-table design pattern with ElectroDB.

Observability Not Supported

DynamoDB storage does not support the observability domain. Traces from the DefaultExporter cannot be persisted to DynamoDB, and Mastra Studio's observability features won't work with DynamoDB as your only storage provider. To enable observability, use composite storage to route observability data to a supported provider like ClickHouse or PostgreSQL.

Item Size Limit

DynamoDB enforces a 400 KB maximum item size. This limit can be exceeded when storing messages with base64-encoded attachments such as images. See Handling large attachments for workarounds including uploading attachments to external storage.

功能
Direct link to 功能

🌐 Features

  • 针对所有Mastra存储需求的高效单表设计
  • 基于 ElectroDB 进行类型安全的 DynamoDB 访问
  • 支持 AWS 凭证、区域和端点
  • 与 AWS DynamoDB 本地环境兼容,适用于开发
  • 存储线程、消息、评估和工作流数据
  • 针对无服务器环境优化
  • 可配置的 TTL(存活时间),用于每种实体类型的数据自动过期

安装
Direct link to 安装

🌐 Installation

npm install @mastra/dynamodb@latest

先决条件
Direct link to 先决条件

🌐 Prerequisites

在使用此软件包之前,你必须创建一个具有特定结构的 DynamoDB 表,包括主键和全局二级索引(GSI)。此适配器期望 DynamoDB 表及其 GSI 由外部进行配置。

🌐 Before using this package, you must create a DynamoDB table with a specific structure, including primary keys and Global Secondary Indexes (GSIs). This adapter expects the DynamoDB table and its GSIs to be provisioned externally.

有关使用 AWS CloudFormation 或 AWS CDK 设置表的详细说明,请参阅 TABLE_SETUP.md。在继续操作之前,请确保你的表已按照这些说明进行配置。

🌐 Detailed instructions for setting up the table using AWS CloudFormation or AWS CDK are available in TABLE_SETUP.md. Please ensure your table is configured according to those instructions before proceeding.

用法
Direct link to 用法

🌐 Usage

基本用法
Direct link to 基本用法

🌐 Basic Usage

import { Memory } from "@mastra/memory";
import { DynamoDBStore } from "@mastra/dynamodb";

// Initialize the DynamoDB storage
const storage = new DynamoDBStore({
id: "dynamodb", // Unique identifier for this storage instance
config: {
tableName: "mastra-single-table", // Name of your DynamoDB table
region: "us-east-1", // Optional: AWS region, defaults to 'us-east-1'
// endpoint: "http://localhost:8000", // Optional: For local DynamoDB
// credentials: { accessKeyId: "YOUR_ACCESS_KEY", secretAccessKey: "YOUR_SECRET_KEY" } // Optional
},
});

// Example: Initialize Memory with DynamoDB storage
const memory = new Memory({
storage,
options: {
lastMessages: 10,
},
});

使用 DynamoDB Local 进行本地开发
Direct link to 使用 DynamoDB Local 进行本地开发

🌐 Local Development with DynamoDB Local

对于本地开发,你可以使用 DynamoDB 本地版

🌐 For local development, you can use DynamoDB Local.

  1. 运行 DynamoDB 本地版(例如,使用 Docker):

    docker run -p 8000:8000 amazon/dynamodb-local
  2. 配置 DynamoDBStore 以使用本地端点:

    import { DynamoDBStore } from "@mastra/dynamodb";

    const storage = new DynamoDBStore({
    id: "dynamodb-local",
    config: {
    tableName: "mastra-single-table", // Ensure this table is created in your local DynamoDB
    region: "localhost", // Can be any string for local, 'localhost' is common
    endpoint: "http://localhost:8000",
    // For DynamoDB Local, credentials are not typically required unless configured.
    // If you've configured local credentials:
    // credentials: { accessKeyId: "fakeMyKeyId", secretAccessKey: "fakeSecretAccessKey" }
    },
    });

    你仍然需要在本地的 DynamoDB 实例中创建表和全局二级索引(GSI),例如,可以使用指向本地端点的 AWS CLI 来操作。

参数
Direct link to 参数

🌐 Parameters

id:

string
Unique identifier for this storage instance.

config.tableName:

string
The name of your DynamoDB table.

config.region?:

string
AWS region. Defaults to 'us-east-1'. For local development, can be set to 'localhost' or similar.

config.endpoint?:

string
Custom endpoint for DynamoDB (e.g., 'http://localhost:8000' for local development).

config.credentials?:

object
AWS credentials object with `accessKeyId` and `secretAccessKey`. If not provided, the AWS SDK will attempt to source credentials from environment variables, IAM roles (e.g., for EC2/Lambda), or the shared AWS credentials file.

config.ttl?:

object
TTL (Time To Live) configuration for automatic data expiration. Configure per entity type: thread, message, trace, eval, workflow_snapshot, resource, score. Each entity config includes: enabled (boolean), attributeName (string, default: 'ttl'), defaultTtlSeconds (number).

TTL(生存时间)配置
Direct link to TTL(生存时间)配置

🌐 TTL (Time To Live) Configuration

DynamoDB TTL 允许你在指定的时间段后自动删除项。这在以下情况下非常有用:

🌐 DynamoDB TTL allows you to automatically delete items after a specified time period. This is useful for:

  • 成本优化:自动删除旧数据以降低存储成本
  • 数据生命周期管理:实现合规的保留策略
  • 性能:防止表格无限增长
  • 隐私合规:在规定期限后自动清除个人数据

启用 TTL
Direct link to 启用 TTL

🌐 Enabling TTL

要使用 TTL,你必须:

🌐 To use TTL, you must:

  1. 在 DynamoDBStore 中配置 TTL(如下所示)
  2. 通过 AWS 控制台或 CLI 在你的 DynamoDB 表上启用 TTL,并指定属性名称(默认值:ttl
import { DynamoDBStore } from "@mastra/dynamodb";

const storage = new DynamoDBStore({
name: "dynamodb",
config: {
tableName: "mastra-single-table",
region: "us-east-1",
ttl: {
// Messages expire after 30 days
message: {
enabled: true,
defaultTtlSeconds: 30 * 24 * 60 * 60, // 30 days
},
// Threads expire after 90 days
thread: {
enabled: true,
defaultTtlSeconds: 90 * 24 * 60 * 60, // 90 days
},
// Traces expire after 7 days with custom attribute name
trace: {
enabled: true,
attributeName: "expiresAt", // Custom TTL attribute
defaultTtlSeconds: 7 * 24 * 60 * 60, // 7 days
},
// Workflow snapshots don't expire
workflow_snapshot: {
enabled: false,
},
},
},
});

支持的实体类型
Direct link to 支持的实体类型

🌐 Supported Entity Types

TTL 可以为以下实体类型配置:

🌐 TTL can be configured for these entity types:

实体描述
thread对话线程
message线程中的消息
trace可观察性跟踪
eval评估结果
workflow_snapshot工作流状态快照
resource用户/资源数据
score评分结果

TTL 实体配置
Direct link to TTL 实体配置

🌐 TTL Entity Configuration

每种实体类型接受以下配置:

🌐 Each entity type accepts the following configuration:

enabled:

boolean
Whether TTL is enabled for this entity type.

attributeName?:

string
The DynamoDB attribute name to use for TTL. Must match the TTL attribute configured on your DynamoDB table. Defaults to 'ttl'.

defaultTtlSeconds?:

number
Default TTL in seconds from item creation time. Items will be automatically deleted by DynamoDB after this duration.

在你的 DynamoDB 表上启用 TTL
Direct link to 在你的 DynamoDB 表上启用 TTL

🌐 Enabling TTL on Your DynamoDB Table

在代码中配置 TTL 后,必须在 DynamoDB 表本身上启用 TTL:

🌐 After configuring TTL in your code, you must enable TTL on the DynamoDB table itself:

使用 AWS CLI:

aws dynamodb update-time-to-live \
--table-name mastra-single-table \
--time-to-live-specification "Enabled=true, AttributeName=ttl"

使用 AWS 控制台:

  1. 前往 DynamoDB 控制台
  2. 请选择你的桌子
  3. 转到“附加设置”选项卡
  4. 在“生存时间 (TTL)”下,点击“管理 TTL”
  5. 启用 TTL 并指定属性名称(默认:ttl

注意:DynamoDB 会在过期后 48 小时内删除过期项目。在实际删除之前,这些项目仍然可以被查询。

AWS IAM 权限
Direct link to AWS IAM 权限

🌐 AWS IAM Permissions

执行代码的 IAM 角色或用户需要具备与指定 DynamoDB 表及其索引交互的适当权限。下面是一个示例策略。将 ${YOUR_TABLE_NAME} 替换为你的实际表名,将 ${YOUR_AWS_REGION}${YOUR_AWS_ACCOUNT_ID} 替换为适当的值。

🌐 The IAM role or user executing the code needs appropriate permissions to interact with the specified DynamoDB table and its indexes. Below is a sample policy. Replace ${YOUR_TABLE_NAME} with your actual table name and ${YOUR_AWS_REGION} and ${YOUR_AWS_ACCOUNT_ID} with appropriate values.

{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"dynamodb:DescribeTable",
"dynamodb:GetItem",
"dynamodb:PutItem",
"dynamodb:UpdateItem",
"dynamodb:DeleteItem",
"dynamodb:Query",
"dynamodb:Scan",
"dynamodb:BatchGetItem",
"dynamodb:BatchWriteItem"
],
"Resource": [
"arn:aws:dynamodb:${YOUR_AWS_REGION}:${YOUR_AWS_ACCOUNT_ID}:table/${YOUR_TABLE_NAME}",
"arn:aws:dynamodb:${YOUR_AWS_REGION}:${YOUR_AWS_ACCOUNT_ID}:table/${YOUR_TABLE_NAME}/index/*"
]
}
]
}

关键考虑因素
Direct link to 关键考虑因素

🌐 Key Considerations

在深入了解架构细节之前,在使用 DynamoDB 存储适配器时请记住以下关键点:

🌐 Before diving into the architectural details, keep these key points in mind when working with the DynamoDB storage adapter:

  • 外部表配置: 此适配器_要求_你在使用适配器之前自行创建并配置 DynamoDB 表及其全局二级索引(GSI)。请按照 TABLE_SETUP.md 中的指南操作。
  • 单表设计: 所有 Mastra 数据(线程、消息等)都存储在一个 DynamoDB 表中。这是一种针对 DynamoDB 优化的刻意设计选择,与关系型数据库的做法不同。
  • 理解GSI: 熟悉GSI的结构(根据 TABLE_SETUP.md)对于理解数据检索和潜在的查询模式非常重要。
  • ElectroDB: 该适配器使用 ElectroDB 来管理与 DynamoDB 的交互,为原始 DynamoDB 操作提供了抽象层和类型安全性。

架构方法
Direct link to 架构方法

🌐 Architectural Approach

此存储适配器使用 单表设计模式,并利用 ElectroDB,这是 DynamoDB 的一种常见且推荐的方法。这在架构上不同于关系型数据库适配器(如 @mastra/pg@mastra/libsql),后者通常使用多个表,每个表专用于特定实体(线程、消息等)。

🌐 This storage adapter utilizes a single-table design pattern leveraging ElectroDB, a common and recommended approach for DynamoDB. This differs architecturally from relational database adapters (like @mastra/pg or @mastra/libsql) that typically use multiple tables, each dedicated to a specific entity (threads, messages, etc.).

这种方法的关键方面:

🌐 Key aspects of this approach:

  • DynamoDB 原生: 单表设计针对 DynamoDB 的键值和查询能力进行了优化,相比模仿关系模型,通常能带来更好的性能和可扩展性。
  • 外部表管理: 与某些可能提供通过代码创建表的辅助功能的适配器不同,该适配器期望在使用前,DynamoDB 表及其关联的全局二级索引 (GSI) 已经在外部配置好。请参考 TABLE_SETUP.md 获取使用 AWS CloudFormation 或 CDK 等工具的详细说明。该适配器仅专注于与预先存在的表结构进行交互。
  • 通过接口实现一致性: 虽然底层存储模型不同,但此适配器遵循与其他适配器相同的 MastraStorage 接口,确保它可以在 Mastra Memory 组件中互换使用。

单表中的主数据
Direct link to 单表中的主数据

🌐 Mastra Data in the Single Table

在单个 DynamoDB 表中,不同的 Mastra 数据实体(如 Threads、Messages、Traces、Evals 和 Workflows)使用 ElectroDB 进行管理和区分。ElectroDB 为每种实体类型定义了特定的模型,这些模型包括唯一的键结构和属性。这使适配器能够在同一表中高效地存储和检索多种数据类型。

🌐 Within the single DynamoDB table, different Mastra data entities (such as Threads, Messages, Traces, Evals, and Workflows) are managed and distinguished using ElectroDB. ElectroDB defines specific models for each entity type, which include unique key structures and attributes. This allows the adapter to store and retrieve diverse data types efficiently within the same table.

例如,一个 Thread 项可能有一个像 THREAD#<threadId> 这样的主键,而属于该线程的 Message 项可能使用 THREAD#<threadId> 作为分区键,MESSAGE#<messageId> 作为排序键。全局二级索引(GSI),在 TABLE_SETUP.md 中有详细说明,是经过战略性设计的,以支持这些不同实体的常见访问模式,例如获取某个线程的所有消息或查询与特定工作流相关的跟踪记录。

🌐 For example, a Thread item might have a primary key like THREAD#<threadId>, while a Message item belonging to that thread might use THREAD#<threadId> as a partition key and MESSAGE#<messageId> as a sort key. The Global Secondary Indexes (GSIs), detailed in TABLE_SETUP.md, are strategically designed to support common access patterns across these different entities, such as fetching all messages for a thread or querying traces associated with a particular workflow.

单表设计的优势
Direct link to 单表设计的优势

🌐 Advantages of Single-Table Design

该实现使用 ElectroDB 的单表设计模式,在 DynamoDB 的环境下具有多种优势:

🌐 This implementation uses a single-table design pattern with ElectroDB, which offers several advantages within the context of DynamoDB:

  1. 成本较低(可能): 较少的表可以简化读取/写入容量单位(RCU/WCU)的配置和管理,特别是在按需容量模式下。
  2. 更好的性能: 相关数据可以通过全局二级索引 (GSI) 共同存放或高效访问,从而实现对常见访问模式的快速查找。
  3. 简化管理: 需要监控、备份和管理的表更少。
  4. 降低访问模式的复杂性: ElectroDB 有助于管理单表上的项目类型和访问模式的复杂性。
  5. 事务支持: 如果需要,DynamoDB 事务可以跨存储在同一表中的不同“实体”类型使用。