LoginSignup
3
0

More than 3 years have passed since last update.

Python(boto3)でDynamoDB上のデータを更新しようとすると「ExpressionAttributeNames contains invalid key: Syntax error; key: <キー名>」となる

Last updated at Posted at 2020-03-18

事象

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)

image.png

以上

3
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
0