[AWS] Export and Import Data from DynamoDB Table 从 DynamoDB 数据库中导入和导出数据


DynamoDB 是 AWS 全家桶中非常重要的一个服务,跟 MongoDB 一样,是 NoSQL 数据库。有时候我们需要将某个表的数据整个导出或者导入,如果数据量很大的话,建议使用 AWS Data Pipeline 导出和导入 DynamoDB,如果数据量不是特别大的话,建议使用 AWS CLIjq 来将表内数据转为 json,同时也可以将 json 文件导入回 DynamoDB 数据库,具体可以参考 stackoverflow 上的这个帖子

从云端数据库导出数据:

aws dynamodb scan --table-name my-prod-table | jq '{"my-local-table": [.Items[] | {PutRequest: {Item: .}}]}' > data.json

将数据导入本地数据库:

aws dynamodb batch-write-item --request-items file://data.json --endpoint-url http://localhost:8000

将数据导回云端数据库:

aws dynamodb batch-write-item --request-items file://data.json 

导入数据库的时候有可能会遇到如下错误:

ClientError: An error occurred (ValidationException) when calling the    BatchWriteItem operation: 1 validation error detected: Value .... Map value   must satisfy constraint: [Member must have length less than or equal to 25,   Member must have length greater than or equal to 1]

根据官方文档上的介绍,BatchWriteItem 一次最多只能写 25 个 item,多了的话就只能分块来写了,每次只能读取 25 个。不知为何,博主突然想到了这道 LeetCode 上的题目 Read N Characters Given Read4 II - Call multiple times,好吧,刷题中毒太深了^.^|||~ 解决方法可以参考 stackoverflow 上的这个帖子,需要使用 AWS 针对 Python 开发的 SDK,boto,参见代码如下:

import json
import boto3

def batch(iterable, n=1):
    l = len(iterable)
    for ndx in range(0, l, n):
        yield iterable[ndx:min(ndx + n, l)]

client = boto3.client('dynamodb')

with open('data.json') as f:
    batch_dict = json.load(f)

for x in batch(batch_dict['scraper_exact_urls'], 25):
    subbatch_dict = {'scraper_exact_urls': x}
    response = client.batch_write_item(RequestItems=subbatch_dict)

参考资料:

https://docs.aws.amazon.com/zh_cn/amazondynamodb/latest/developerguide/DynamoDBPipeline.html

https://aws.amazon.com/cli/

https://stedolan.github.io/jq/

https://stackoverflow.com/questions/18896329/export-data-from-dynamodb

https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_BatchWriteItem.html

https://stackoverflow.com/questions/40941231/aws-cli-dynamo-db-validationexception-error

https://boto3.amazonaws.com/v1/documentation/api/latest/index.html

posted @ 2020-05-13 10:18  Grandyang  阅读(1305)  评论(0编辑  收藏  举报
Fork me on GitHub