0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

AWS DynamoDB メモ 項目削除ではまったこと

Last updated at Posted at 2022-05-02

エラーと原因

  • エラーメッセージ
[ERROR] ClientError: An error occurred (ValidationException) when calling the DeleteItem operation: The provided key element does not match the schema
  • 原因

DynamoDB.Table() クラスの delete_item() メソッドの Key 引数にプライマリキー以外のキーを指定していた

  • 関連するドキュメント

A map of attribute names to AttributeValue objects, representing the primary key of the item to delete.

For the primary key, you must provide all of the attributes. For example, with a simple primary key, you only need to provide a value for the partition key. For a composite primary key, you must provide values for both the partition key and the sort key.

プライマリキーと削除したい項目

  • プライマリキー
パーティションキー ソートキー
year title
  • 削除したい項目
{
  "year": {
    "N": "2000"
  },
  "title": {
    "S": "sample movie"
  }
  "director": {
    "S": "sample director"
  }
}

コード例

うまくいかないコード

lambda_function.py
import json
import boto3
import decimal

dynamodb = boto3.resource('dynamodb')

def delete_movie(item):
    """
    項目削除メソッド
    """
    table = dynamodb.Table('sample-table')
    table.delete_item(
       Key={
            'year': decimal.Decimal(item['year']),
            'title': item['title'],
            'director': item['director']
        }
    )

def lambda_handler(event, context):
    item = {
        'year': event['year'],
        'title': event['title'],
        'director': event['director']
    }
    delete_movie(item)

うまくいくコード

lambda_function.py
import json
import boto3
import decimal

dynamodb = boto3.resource('dynamodb')

def delete_movie(item):
    """
    項目削除メソッド
    """
    table = dynamodb.Table('sample-table')
    # Key にはパーティションキーとソートキーのみ指定する
    table.delete_item(
       Key={
            'year': decimal.Decimal(item['year']),
            'title': item['title']
        }
    )

def lambda_handler(event, context):
    item = {
        'year': event['year'],
        'title': event['title'],
        'director': event['director']
    }
    delete_movie(item)

参考記事

0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?