You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在AWS CDK的DynamoDB TableV2中指定Attribute属性?

使用AWS CDK TableV2创建DynamoDB表时指定Attribute属性

Attribute结构体的作用与基础说明

Attribute结构体用来定义DynamoDB表的各类键属性,包括:

  • 表的分区键(Partition Key)、排序键(Sort Key)
  • 全局二级索引(GSI)、本地二级索引(LSI)的键属性

它包含两个必填字段:

  • name: 属性的名称(字符串类型)
  • type: 属性的数据类型,可选值为AttributeType.STRING、AttributeType.NUMBER、AttributeType.BINARY

两种使用方式

1. 内联定义(你当前的写法)

你现在配置partitionKey的方式,本质就是直接内联使用Attribute的结构,这是日常开发中最常用的写法:

var clientLoanData = new dynamodb.TableV2(this, "X", {
    partitionKey: {
        name: "LoanFileIngestionCustomerID",
        type: dynamodb.AttributeType.STRING,
    },
    removalPolicy: RemovalPolicy.DESTROY
});

2. 先实例化Attribute对象再传入

如果需要复用属性定义(比如多个索引用到相同属性),可以先创建Attribute实例再传入:

// 预先定义Attribute对象
const customerIdAttr = dynamodb.Attribute.fromNameAndType(
    "LoanFileIngestionCustomerID",
    dynamodb.AttributeType.STRING
);

// 创建表时传入该实例
var clientLoanData = new dynamodb.TableV2(this, "X", {
    partitionKey: customerIdAttr,
    removalPolicy: RemovalPolicy.DESTROY
});

扩展示例:带排序键与全局二级索引的表

如果要给表添加排序键,或者创建全局二级索引,同样用Attribute来定义对应的键:

var clientLoanData = new dynamodb.TableV2(this, "X", {
    partitionKey: {
        name: "LoanFileIngestionCustomerID",
        type: dynamodb.AttributeType.STRING,
    },
    // 用Attribute定义排序键
    sortKey: {
        name: "LoanFileID",
        type: dynamodb.AttributeType.STRING,
    },
    // 用Attribute定义全局二级索引的键
    globalIndexes: [
        {
            indexName: "LoanStatusIndex",
            partitionKey: {
                name: "LoanStatus",
                type: dynamodb.AttributeType.STRING,
            },
            projectionType: dynamodb.ProjectionType.ALL
        }
    ],
    removalPolicy: RemovalPolicy.DESTROY
});

内容的提问来源于stack exchange,提问作者Micah Armantrout

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 01:31:14