简体   繁体   English

使用 boto3 更新 DynamoDb

[英]DynamoDb update using boto3

I am writing a lambda function to update dynamodb item.我正在写一个 lambda function 来更新 dynamodb 项目。 But the problem is that when I give但问题是当我给

 {
  "employee_id": "1",
  "last_name": "jane",
  "first_name": "anderson"
}

It works fine but if you remove the last_name or the first_name the program crashes.I want to make it dynamic like if I provice last_name and employee_id it changes last_name only and same goes with first_name.它工作正常,但如果你删除 last_name 或 first_name 程序崩溃。我想让它动态化,就像我提供 last_name 和 employee_id 它只改变 last_name 和 first_name 一样。 If I provide both first_name and last_name it changes both.如果我提供 first_name 和 last_name 两者都会改变。 Note: employee_id is used here to fetch the data

 {
  "employee_id": "1",
  "last_name": "jane"
}

It gives an error saying that:它给出了一个错误说:

{
  "errorMessage": "'first_name'",
  "errorType": "KeyError",
  "stackTrace": [
    "  File \"/var/task/lambda_function.py\", line 10, in lambda_handler\n    first_name= event['first_name']\n"
  ]
}

Lambda function: Lambda function:

import boto3
import json

dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('Employee')

def lambda_handler(event, context):
    employee_id = event['employee_id']
    last_name= event['last_name']
    first_name= event['first_name']
    update = table.update_item(
        Key={
            'employee_id': employee_id
        },
        ConditionExpression= 'attribute_exists(employee_id)',
        UpdateExpression='SET first_name = :val1, last_name = :val2',
        ExpressionAttributeValues={
            ':val1': last_name,
            ':val2': first_name
        }
    )

There are few possibilities you could deal with the issue.您可以处理该问题的可能性很小 If the first_name is absent you could either skip the filed in DynamoDB, or provide some default/empty value.如果first_name不存在,您可以跳过 DynamoDB 中的字段,或提供一些默认/空值。 This is use-case specific and depends on how you want to deal with the missing first_name .这是特定于用例的,取决于您想如何处理丢失的first_name You could also throw an error if such situation should not be allowed.如果不允许这种情况,您也可以抛出错误。

Either way, there is a check performed if first_name exists in the event .无论哪种方式,如果first_name存在于event ,都会执行检查

Below, is an example of the first option:下面是第一个选项的示例

import boto3
import json

dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('Employee-wahaj')

def lambda_handler(event, context):

    employee_id = event['employee_id']
    last_name = event['last_name']

    UpdateExpression = 'SET last_name = :val1'
    ExpressionAttributeValues = {':val1': last_name }


    if 'first_name' in event:
        
        first_name= event['first_name']
        UpdateExpression = 'SET last_name = :val1, first_name = :val2'
        ExpressionAttributeValues = {
                ':val1': last_name,
                ':val2': first_name
            }

    update = table.update_item(
        Key={
            'employee_id': employee_id
        },
        ConditionExpression= 'attribute_exists(employee_id)',
        UpdateExpression=UpdateExpression,
        ExpressionAttributeValues=ExpressionAttributeValues
    )

update for first and last names更新名字和姓氏

Its a basic solution (just few if-else-if), as I don't want to over complicate the example.它是一个基本的解决方案(只有少数 if-else-if),因为我不想让示例过于复杂。

import boto3
import json

dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('Employee-wahaj')

def lambda_handler(event, context):

    employee_id = event['employee_id']

    if 'first_name' in event and 'last_name' not in event:

        first_name = event['first_name']
        UpdateExpression = 'SET first_name = :val1'
        ExpressionAttributeValues = {':val1': first_name }

    elif 'last_name' in event and 'first_name' not in event:

        last_name = event['last_name']
        UpdateExpression = 'SET last_name = :val1'
        ExpressionAttributeValues = {':val1': last_name}

    elif 'first_name' in event and 'last_name' in event:

        last_name = event['last_name']
        first_name= event['first_name']
        UpdateExpression = 'SET last_name = :val1, first_name = :val2'
        ExpressionAttributeValues = {
                ':val1': last_name,
                ':val2': first_name
            }

    else:
        raise ValueError("first_name and last_name not given")


    update = table.update_item(
        Key={
            'employee_id': employee_id
        },
        ConditionExpression= 'attribute_exists(employee_id)',
        UpdateExpression=UpdateExpression,
        ExpressionAttributeValues=ExpressionAttributeValues
    )

I wrote this quick generic routine that allows you to parse the JSON and extract the values and append it in a dictionary form for the update.我编写了这个快速通用例程,它允许您解析 JSON 并提取值和 append 以字典形式进行更新。 The key field is located in the data argument.关键字段位于数据参数中。

def updateItem(data):
  rollNo = data['keyField']

  updateExp = "SET "
  expAttribVal = {}
  count = 1

  for key, value in data.items():
    if key != "keyField": 
        if count != 1:
            updateExp = updateExp+", "
        updateExp = updateExp + key + " = :val"+str(count)
        temp = {':val'+str(count) : value}
        expAttribVal.update(temp)
        count=count+1

  try:
    response = table.update_item(
        Key={
            'keyField': keyField
        },
        UpdateExpression=updateExp,
        ExpressionAttributeValues=expAttribVal,
        ReturnValues="UPDATED_NEW"
    )
    return response
  except:
    raise        

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

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