如何使用AWS CDK设置更多AWS DynamoDB表属性
AWS CDK DynamoDB 配置操作说明
不需要在表创建完成后调用SDK的UpdateTable接口修改属性,你提到的预配置吞吐量、属性定义、索引配置,都可以直接通过CDK原生能力完成,具体操作方法如下:
预配置吞吐量设置
你只需要在创建Table实例时指定计费模式为预配置模式,同时传入对应的读写容量参数即可,示例如下:
import * as dynamodb from '@aws-cdk/aws-dynamodb'; import { BillingMode } from '@aws-cdk/aws-dynamodb'; const table = new dynamodb.Table(this, 'Movies', { tableName: 'Movies', // 分区键 partitionKey: { name: 'year', type: dynamodb.AttributeType.NUMBER }, // 排序键 sortKey: { name: 'title', type: dynamodb.AttributeType.STRING }, // 指定计费模式为预配置 billingMode: BillingMode.PROVISIONED, // 配置预配置吞吐量 readCapacity: 10, writeCapacity: 10, });
AttributeDefinitions配置
CDK不需要你手动声明完整的AttributeDefinitions列表,它会自动根据你配置的主键、排序键、所有索引用到的属性,自动生成对应的属性定义配置,无需额外手动操作。
索引配置
索引分为全局二级索引(GSI)和本地二级索引(LSI)两种,配置方法如下:
- 全局二级索引可以在创建表时直接传入配置,也可以在表实例创建完成后调用内置方法添加
- 本地二级索引仅支持在创建表时配置,无法后续添加
代码示例:
// 方法1:创建表时直接传入GSI和LSI配置 const table = new dynamodb.Table(this, 'Movies', { partitionKey: { name: 'year', type: dynamodb.AttributeType.NUMBER }, sortKey: { name: 'title', type: dynamodb.AttributeType.STRING }, billingMode: BillingMode.PROVISIONED, readCapacity: 10, writeCapacity: 10, // 配置全局二级索引 globalSecondaryIndexes: [{ indexName: 'GenreIndex', partitionKey: { name: 'genre', type: dynamodb.AttributeType.STRING }, sortKey: { name: 'release_date', type: dynamodb.AttributeType.NUMBER }, // 可单独配置GSI的吞吐量 readCapacity: 5, writeCapacity: 5, projectionType: dynamodb.ProjectionType.ALL, }], // 配置本地二级索引 localSecondaryIndexes: [{ indexName: 'RatingIndex', sortKey: { name: 'rating', type: dynamodb.AttributeType.NUMBER }, projectionType: dynamodb.ProjectionType.ALL, }] }); // 方法2:创建表实例后调用方法添加GSI table.addGlobalSecondaryIndex({ indexName: 'DirectorIndex', partitionKey: { name: 'director', type: dynamodb.AttributeType.STRING }, projectionType: dynamodb.ProjectionType.KEYS_ONLY, });
特殊参数配置补充
如果需要配置高层Table构造没有暴露的特殊参数,你可以通过逃逸 hatch 直接修改底层CfnTable资源的属性,示例如下:
// 获取底层的CfnTable实例 const cfnTable = table.node.defaultChild as dynamodb.CfnTable; // 直接修改底层属性,支持所有DynamoDB CreateTable接口支持的参数 cfnTable.addPropertyOverride('DeletionProtectionEnabled', true);
内容的提问来源于stack exchange,提问作者Armen Babakanian
相关产品推荐
相关产品推荐

