简体   繁体   English

仅更新给定的值并忽略 dynamodb 中的其他值

[英]Only update the value given and ignore other values in dynamodb

Hi I am writing a lambda function that will update the DynamoDb using boto3.嗨,我正在编写一个 lambda 函数,它将使用 boto3 更新 DynamoDb。 In this code employee_id is auto-generated but you have to provide last_name or first_name .在这段代码中, employee_id是自动生成的,但您必须提供last_namefirst_name I am doing it with if-else .我正在使用if-else If the attribute tends to increase so does the checks.如果属性趋于增加,检查也会增加。 I can't keep on going with if condition.我无法继续使用 if 条件。 How can I tackle this what changes should I make我该如何解决这个问题我应该做出哪些改变

import boto3
import json

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

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
    )

The code that I came up with but is not working我想出但不起作用的代码

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']
    column = [first_name,last_name]
    for i in range(0,len(column):
       query = 'SET {} = :val1,:val2'.format(column[i])
       response = table.update_item(
           Key={
            'employee_id': employee_id
            },
            ConditionExpression= 'attribute_exists(employee_id)',
            UpdateExpression = query,
            ExpressionAttributeValues={
                ':val1': first_name,
                ':val2': last_name
            },
            ReturnValues="UPDATED_NEW"
        )

You should look at storing the update expression and expression values separately, then passing the complete set into the Lambda function.您应该考虑分别存储更新表达式和表达式值,然后将完整集传递到 Lambda 函数中。

This would also allow you to validate against each parameter (perhaps breaking this into a validate function to avoid excessive size of function).这也将允许您针对每个参数进行验证(可能将其分解为验证函数以避免函数过大)。 This way you support both required and optional parameters, then at the end validate that the update expression has valid parameters.通过这种方式,您可以同时支持必需参数和可选参数,然后在最后验证更新表达式是否具有有效参数。

Perhaps something like the below?也许像下面这样?

import boto3
import json

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

def lambda_handler(event, context):

    update_expression_values = []
    expression_attribute_values = {}
    
    if 'employee_id' in event:
        employee_id = event['employee_id']
    else:
        raise ValueError("employee_id not given")
    
    if 'first_name' in event:
        update_expression_values.append('first_name = :val_first_name')
        expression_attribute_values[':val_first_name'] = event['first_name']

    if 'last_name' in event:

        update_expression_values.append('last_name = :val_last_name')
        expression_attribute_values[':val_last_name'] = event['last_name']

    if len(update_expression_values) < 1:
        raise ValueError("first_name and last_name not given")

    seperator = ','
    
    update = table.update_item(
        Key={
            'employee_id': employee_id
        },
        ConditionExpression= 'attribute_exists(employee_id)',
        UpdateExpression='SET ' + seperator.join(update_expression_values),
        ExpressionAttributeValues=expression_attribute_values
    )

This could be broken down further to reuse the logic through a function that can perform these checks such as the below.这可以进一步分解以通过可以执行这些检查的函数重用逻辑,如下所示。

import boto3
import json

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

update_expression_values = []
expression_attribute_values = {}

def lambda_handler(event, context):
    global update_expression_values
    global expression_attribute_values
    
    update_expression_values = []
    expression_attribute_values = {}

    if 'employee_id' in event:
        employee_id = event['employee_id']
    else:
        raise ValueError("employee_id not given")
        
    process_event_key(event, 'first_name')
    process_event_key(event, 'last_name')
    process_event_key(event, 'new_value')

    if len(update_expression_values) < 1:
        raise ValueError("first_name and last_name not given")

    seperator = ','
    
    update = table.update_item(
        Key={
            'employee_id': employee_id
        },
        ConditionExpression= 'attribute_exists(employee_id)',
        UpdateExpression='SET ' + seperator.join(update_expression_values),
        ExpressionAttributeValues=expression_attribute_values
    )
    
def process_event_key(event, key):
    global update_expression_values
    global expression_attribute_values
    
    if key in event:
        update_expression_values.append(key + ' = :val_' + key)
        expression_attribute_values[':val_' + key] = event[key]

Test Event测试活动

{
  "new_value": "test",
  "employee_id": "value2",
  "last_name": "value3",
  "first_name": "value4"
}

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

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