ソースコード
put_item_dynamo.py
import botocore
import boto3
from boto3.dynamodb.conditions import Key, Attr
dynamodb = boto3.resource('dynamodb')
# ①boto3からdynamoClientオブジェクトを生成
dynamoClient = boto3.client('dynamodb')
def put_item_dynamo():
tableName = 'YourDynamoDBName'
val1 = 'abc'
val2 = 'efg'
val3 = 'hij'
val4 = 1
# ②挿入するアイテムをdictionary形式で生成
item = {
'column_1' : {'S' : val1},
'column_2' : {'S' : val2},
'column_3' : {'S' : val3},
'column_4' : {'N' : str(val4)} # @数値型は文字列型にキャストする必要あり
}
# ③一意制約オプション( column_1 と colmun_2 の複合主キーで制約)
condition = 'attribute_not_exists({0}) AND attribute_not_exists({1})'.format('column_1', 'column_2')
# ④レコード挿入実行
try:
response = dynamoClient.put_item(
TableName=tableName,
Item=item,
ConditionExpression=condition
)
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'ConditionalCheckFailedException':
print('一意制約違反のため、DynamoDbへの挿入失敗。すでに同様のキーのレコードが存在します。' + \
'TableName={0}, Item={1}, ConditionExpression={2}'.format(tableName, item, condition))
return True
else:
print('DynamoDB挿入中に想定外のエラーが発生しました。' + \
'TableName={0}, Item={1}, ConditionExpression={2}, Error={3}'.format(tableName, item, condition, e))
return False
print('Dynamoに挿入完了。item={0}, response={1}'.format(str(item), response))
return True
解説
概要
手順としては簡単です。
①boto3からdynamoClientオブジェクトを生成
②挿入するアイテムをdictionary形式で生成
③一意制約オプションを設定(任意)
④dynamoClientを利用して、レコードを挿入
以下注意が必要な部分だけ詳細を記載します。
②挿入するアイテムをdictionary形式で生成
まず、dictionary形式で挿入するアイテムのオブジェクトを生成します。
keyはカラム名でvalueは挿入したい値になります。
valueの方は、さらにオブジェクトが入れ子になっており、{データタイプ、 値}となっているので注意が必要です。
データ型の設定については以下を参照ください。
一部抜粋
Item={
'string':{ # カラム名
'S':'string',
'N':'string',
'B':b'bytes',
'SS':[
'string',
],
'NS':[
'string',
],
'BS':[
b'bytes',
],
'M':{
'string':{'...recursive...'}
},
'L':[
{'...recursive...'},
],
'NULL':True|False,
'BOOL':True|False
}
また、数値は文字列にキャストする必要があったりとデータ型によって対応が異なってくるため、ここも注意が必要です。
③一意制約オプションを設定(任意)
サンプルでは一意制約を設定していますが、ここの制約はいろいろな設定ができます。
詳しくは以下を参照下さい。