- 追加された行はこの色です。
- 削除された行はこの色です。
[[AWSメモ]] >
* DynamoDBのテストデータ作成メモ [#k9b92eef]
#setlinebreak(on)
※大量データをインポート/エクスポートする場合は AWS Data Pipeline 使った方が良さそう
ここでは boto3 からの投入例を記載するが、大量データをインポート/エクスポートする場合は AWS Data Pipeline 使った方が良さそう
https://docs.aws.amazon.com/ja_jp/datapipeline/latest/DeveloperGuide/dp-importexport-ddb.html
#mycode2(){{
import boto3
import datetime
import decimal
import json
if __name__ == '__main__':
now = datetime.datetime.now()
file_datetime = now.strftime('%Y%m%d_%H%M%S')
TABLE_NAME = 'Books'
DATA_COUNT = 200
FILE_PATH = f'data/{TABLE_NAME}_{file_datetime}.json'
# データファイル作成(念の為、登録データをファイルに退避しておく)
current_datetime = now.strftime('%Y-%m-%d %H:%M:%S')
with open(FILE_PATH, "w") as f:
f.write('[\n')
delimiter = ''
for i in range(DATA_COUNT):
no = i + 1
rec = {
'id': no,
'isbn': '0000-{0:04d}'.format(no),
'title': 'title-{0:04d}'.format(no),
'price': 100 + i,
'created_at': current_datetime,
'updated_at': current_datetime
}
rec_json = delimiter + json.dumps(rec, default=decimal.Decimal, indent=4) + "\n"
f.write(rec_json)
delimiter = ','
f.write(']\n')
# データをロード
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table(TABLE_NAME)
with open(FILE_PATH) as json_file:
import_data = json.load(json_file, parse_float=decimal.Decimal)
with table.batch_writer() as batch:
for rec in import_data:
item = rec
batch.put_item(Item=item)
}}