简体   繁体   English

DynamoDB - boto3 - batch_write_item:提供的关键元素与架构不匹配

[英]DynamoDB - boto3 - batch_write_item: The provided key element does not match the schema

This issue has been raised before but so far I couldn't find a solution that worked in boto3.之前已经提出过这个问题,但到目前为止我找不到适用于 boto3 的解决方案。 GSI is set on 'solutionId' and partition key being 'emp_id'. GSI 设置为“solutionId”,分区键为“emp_id”。 Basically, I just want to delete all records in the table without deleting the table itself.基本上,我只想删除表中的所有记录而不删除表本身。 What am I missing here?我在这里想念什么?

https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/dynamodb.html#DynamoDB.Client.batch_write_item https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/dynamodb.html#DynamoDB.Client.batch_write_item

table_name = "solutions"
dynamodb_client = boto3.client('dynamodb')
dynamodb_resource = boto3.resource('dynamodb')
table = dynamodb_resource.Table(table_name)

data = table.scan()

delete_list = []
for item in data['Items']:
    delete_list.append({
        'DeleteRequest': {
            'Key': {
                'solutionId': {"S": f'{item["solutionId"]}'}
            }
        }
        }
    )


def list_spliter(list, size):
    return (list[pos:pos + size] for pos in range(0, len(list), size))


for batch in list_spliter(delete_list, 25):

    dynamodb_resource.batch_write_item(RequestItems={
        f'{table_name}': batch
    }
    )

I think there are two small issues here:我认为这里有两个小问题:

  1. you're using the high-level resource interface so you don't need to explicitly tell DynamoDB what the attribute types are, they are inferred through automatic marshaling.您正在使用高级资源接口,因此您无需明确告诉 DynamoDB 属性类型是什么,它们是通过自动封送处理推断出来的。 So you can simply use "key": "value" rather than "key": {"S": "value"} for the string keys所以你可以简单地使用"key": "value"而不是"key": {"S": "value"}作为字符串键
  2. when deleting an item you need to provide the full primary key, to include both partition key and sort key删除项目时,您需要提供完整的主键,包括分区键和排序键

So, for example, if your partition and sort keys are named pk and sk :因此,例如,如果您的分区和排序键名为pksk

'DeleteRequest': {
    'Key': {
        'pk': pk,
        'sk': sk
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM