如何在主要表更改时迁移 dynamodb 数据?

nen*_*nTi 5 aws-cloudformation amazon-dynamodb serverless-framework

在开发结构和需求变化期间。需要更改键和索引设置,这可能会破坏增量表更新。所以到目前为止我的解决方案是删除该表并从 cloudformation 堆栈中重新创建它。

但是如何通过生产部署来解决这个问题呢?是否可以按如下方式自动化 dynamodb 部署?

  1. 创建新表
  2. 将数据从旧表迁移到新表
  3. 删除旧表

Joh*_*her 3

是的,完全有可能实现这样的部署结构的自动化。只要您有创建表的代码,就应该相当简单地从旧表中获取所有数据,更改数据,然后将其全部上传到新表,而不会影响正常运行时间。如果你写下你想用什么语言做这样的事情,我可以提供更多帮助。

我之前已经这样做过,并且在下面添加了一个小型通用代码示例,说明如何在 Java 中执行此操作。

给定 dynamo 中存储的对象类型的类来创建表的 Java 方法:

 /**
 * Creates a single table with its appropriate configuration (CreateTableRequest)
 */
public void createTable(Class tableClass) {
    DynamoDBMapper mapper = createMapper(); // you'll need your own function to do this.

    ProvisionedThroughput pt = new ProvisionedThroughput(1L, 1L);
    CreateTableRequest ctr = mapper.generateCreateTableRequest(tableClass);
    ctr.withProvisionedThroughput(new ProvisionedThroughput(1L, 1L));

    // Provision throughput and configure projection for secondary indices.
    if (ctr.getGlobalSecondaryIndexes() != null) {
        for (GlobalSecondaryIndex idx : ctr.getGlobalSecondaryIndexes()) {
            if (idx != null) {
                idx.withProvisionedThroughput(pt).withProjection(new Projection().withProjectionType("ALL"));
            }
        }
    }

    TableUtils.createTableIfNotExists(client, ctr);
}
Run Code Online (Sandbox Code Playgroud)

Java删除表的方法:

private static void deleteTable(String tableName) {
    AmazonDynamoDB client = AmazonDynamoDBClientBuilder.standard().build();
    DynamoDB dynamoDB = new DynamoDB(client);
    Table table = dynamoDB.getTable(tableName);
    try {
        System.out.println("Issuing DeleteTable request for " + tableName);
        table.delete();
        System.out.println("Waiting for " + tableName + " to be deleted...this may take a while...");
        table.waitForDelete();

    }
    catch (Exception e) {
        System.err.println("DeleteTable request failed for " + tableName);
        System.err.println(e.getMessage());
    }
}
Run Code Online (Sandbox Code Playgroud)

我会扫描整个表并将所有内容放入列表中,然后映射该列表,将对象转换为新类型,然后创建该类型的新表但名称不同,推送所有新的对象,然后在将旧表的任何引用切换到新表后删除旧表。不幸的是,这确实意味着消耗表的所有内容都需要能够在两个临时表之间切换。