首页 > 解决方案 > 更新 DynamoDB 时出现客户端错误?

问题描述

代码如下

import boto3
dynamodb = boto3.resource ('dynamodb')
table =dynamodb.Table('test')
def lambda_handler(event, context):
    response = table.update_item(
        Key={
            'id': "100",
            'name': "David"
            })

我创建了一个 DynamoDB 表,test我的主键id是字符串。

在 DynamoDB 中,我的表值id 100John我需要更新为 David。以上是代码。为什么错误抛出元模式

完整错误如下

"errorMessage": "调用UpdateItem操作时发生错误(ValidationException):更新表达式中提供的文档路径对更新无效", "errorType": "ClientError",

试过下面的代码

import boto3
dynamodb = boto3.resource ('dynamodb')
table =dynamodb.Table('test')
def lambda_handler(event, context):
    response = table.update_item(
    Key={
        'id': '100'
        },
    UpdateExpression='SET name = :val1',
    ExpressionAttributeValues={
        ':val1': 'David'
    })

再添加一张表来复制案例

放表:输出>>成功

首先newTable在 DynamoDB 中创建表

import boto3

def lambda_handler(event, context):
    dynamodb = boto3.resource ('dynamodb')
    table =dynamodb.Table('newTable')
    response = table.put_item(
    Item={
        'username': 'Ac',
        'first_name': 'DEF',
        'last_name': 'FHI',
        'age': 10,
        'account': 'GOld'
    })

如何获得物品?输出>>错误

import boto3

def lambda_handler(event, context):
    dynamodb = boto3.resource ('dynamodb')
    table =dynamodb.Table('newTable')
    response = table.get_item(
        Key={
            'username':'Ac'
        }
        )
    print (response)

错误>>响应:“errorMessage”:“调用GetItem操作时发生错误(ValidationException):提供的关键元素与架构不匹配”,“errorType”:“ClientError”,

标签: pythonamazon-web-servicesaws-lambdaamazon-dynamodb

解决方案


第二个答案

get 和 update 需要更新的确切项目而不是批量,因此您还需要提供相应的排序键

礼貌@Sairsreenivas

import boto3

def lambda_handler(event, context):
    dynamodb = boto3.resource ('dynamodb')
    table =dynamodb.Table('newTable')
    # response = table.put_item(
    # Item={
    #     'username': 'Ac',
    #     'first_name': 'DEF',
    #     'last_name': 'GH',
    #     'age': 10,
    #     'account': 'GOld'
    # })
    # try:
    #     response = table.get_item(Key={'username':'Mak'})
    # except Exception as e:
    #     print(e.response['Error']['Message'])
    # else:
    #     return response['Item']
    # item = response['Item']
    # print (item)
    #Get Item
    response = table.get_item(Key={'username':'Ac', 'last_name':'GH'})
    print (response['Item'])
    table.update_item(
        Key ={
            'username':'Ac', 'last_name':'GH'
        },
        UpdateExpression = 'SET age = :value1',
        ExpressionAttributeValues={
            ':value1':20
        }
        )
    print ("After update \n")
    response = table.get_item(Key={'username':'Ac', 'last_name':'GH'})
    print (response['Item'])

推荐阅读