amazon-web-services - 使用带有分区键和排序键的 bash 删除 DynamoDB 表中的所有项目

标签 amazon-web-services amazon-dynamodb aws-cli

我正在尝试使用 bash 中的 AWS CLI 删除具有分区和排序键的 DynamoDB 表中的所有项目。 The best thing I've found so far 是:

aws dynamodb scan --table-name $TABLE_NAME --attributes-to-get "$KEY" \
--query "Items[].$KEY.S" --output text | \
tr "\t" "\n" | \
xargs -t -I keyvalue aws dynamodb delete-item --table-name $TABLE_NAME \
--key "{\"$KEY\": {\"S\": \"keyvalue\"}}"

但这不适用于同时具有分区键和排序键的表,而且我还无法使其与这样的表一起使用。知道如何修改脚本以使其适用于具有复合键的表吗?

最佳答案

根据您 table 的大小,这可能太昂贵并导致停机。请记住,删除的成本与写入的成本相同,因此您将受到预配置的 WCU 的限制。删除并重新创建表会更简单、更快。

# this uses jq but basically we're just removing 
# some of the json fields that describe an existing 
# ddb table and are not actually part of the table schema/defintion
aws dynamodb describe-table --table-name $table_name | jq '.Table | del(.TableId, .TableArn, .ItemCount, .TableSizeBytes, .CreationDateTime, .TableStatus, .ProvisionedThroughput.NumberOfDecreasesToday)' > schema.json
# delete the table
aws dynamodb delete-table --table-name $table_name
# create table with same schema (including name and provisioned capacity)
aws dynamodb create-table --cli-input-json file://schema.json

如果你真的想要你可以单独删除每个项目并且你在正确的轨道上你只需要在你的扫描投影和删除命令中指定哈希和范围键。
aws dynamodb scan \
  --attributes-to-get $HASH_KEY $RANGE_KEY \
  --table-name $TABLE_NAME --query "Items[*]" \
  # use jq to get each item on its own line
  | jq --compact-output '.[]' \
  # replace newlines with null terminated so 
  # we can tell xargs to ignore special characters 
  | tr '\n' '\0' \
  | xargs -0 -t -I keyItem \
    # use the whole item as the key to delete (dynamo keys *are* dynamo items)
    aws dynamodb delete-item --table-name $TABLE_NAME --key=keyItem

如果你想变得 super 花哨,你可以使用 describe-table 调用来获取哈希和范围键来填充 $HASH_KEY$RANGE_KEY,但我会把它留给你作为练习。

关于amazon-web-services - 使用带有分区键和排序键的 bash 删除 DynamoDB 表中的所有项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51660198/

相关文章:

amazon-web-services - EC2 在亚马逊网络服务上重新安装 ubuntu

php - 使用产品广告 API 获取亚马逊评级星级和评级计数

amazon-dynamodb - Dynamodb 流运动 - 在两者之间找到不完整的哈希范围

java - 如何忽略 DynamoDB 中 putitem 中的某些字段

amazon-web-services - 在 AWS CLI DynamoDB 查询操作中替换变量值

amazon-web-services - 有没有一种快速方法可以检查 S3 服务器访问日志记录是否正常工作?

php - Amazon S3 删除标记

amazon-web-services - 无法执行 HTTP 请求 : Connect to localhost:4583 for SSM

java - 如何将 Java 枚举与 Amazon DynamoDB 和 AWS SDK v2 结合使用?

amazon-web-services - 如何从命令行使用多个AWS账户?