DynamoDB 是 AWS 全家桶中非常重要的一個服務,跟 MongoDB 一樣,是 NoSQL 數據庫。有時候我們需要將某個表的數據整個導出或者導入,如果數據量很大的話,建議使用 AWS Data Pipeline 導出和導入 DynamoDB,如果數據量不是特別大的話,建議使用 AWS CLI 和 jq 來將表內數據轉為 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://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