Python(boto3)でDynamoDB上のデータを更新しようとすると「ExpressionAttributeNames contains invalid key: Syntax error; key: <キー名>」となる
事象
AWS上に以下のようなDynamoDBテーブルがある。
- テーブル名:
client_id_master
- パーティションキー:
client-id
(str) - アトリビュート:
-
device-time-stamp
(int)
-
今回、このテーブル上のデータのdevice-time-stamp
列の値を、Python(boto3)からupdate_item()
メソッドにより更新する以下のようなコードを作成した。
from datetime import datetime
import boto3
dynamodb = boto3.resource('dynamodb')
now_unix_time = datetime.now().strftime('%s')
clientId = 'ef5b728f4a74aed'
option = {
'Key': {'client-id': clientId},
'UpdateExpression': 'set #device-time-stamp = :timeStamp',
'ExpressionAttributeNames': {
'#device-time-stamp': 'device-time-stamp'
},
'ExpressionAttributeValues': {
':timeStamp': now_unix_time
}
}
table = dynamodb.Table('client_id_master')
table.update_item(**option)
しかし、このコードを実行したところ以下のエラーとなった。
An error occurred (ValidationException) when calling the UpdateItem operation: ExpressionAttributeNames contains invalid key: Syntax error; key: \"#device-time-stamp\""
原因・解決
原因としては、update_item()
のUpdateExpression
で指定する変数名に使える文字には制限があり、今回は#device-time-stamp
に含まれる-
が利用不可文字に該当したためSyntax errorとなっていた。
よって、以下のように変数名を#device_time_stamp
とすることにより正常にコードが実行できるようになった。
from datetime import datetime
import boto3
dynamodb = boto3.resource('dynamodb')
now_unix_time = datetime.now().strftime('%s')
clientId = 'ef5b728f4a74aed'
option = {
'Key': {'client-id': clientId},
'UpdateExpression': 'set #device_time_stamp = :timeStamp',
'ExpressionAttributeNames': {
'#device_time_stamp': 'device-time-stamp'
},
'ExpressionAttributeValues': {
':timeStamp': now_unix_time
}
}
table = dynamodb.Table('client_id_master')
table.update_item(**option)
以上
Author And Source
この問題について(Python(boto3)でDynamoDB上のデータを更新しようとすると「ExpressionAttributeNames contains invalid key: Syntax error; key: <キー名>」となる), 我々は、より多くの情報をここで見つけました https://qiita.com/r-wakatsuki/items/118ef8fb509d145af306著者帰属:元の著者の情報は、元のURLに含まれています。著作権は原作者に属する。
Content is automatically searched and collected through network algorithms . If there is a violation . Please contact us . We will adjust (correct author information ,or delete content ) as soon as possible .