簡體   English   中英

僅更新給定的值並忽略 dynamodb 中的其他值

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

嗨,我正在編寫一個 lambda 函數,它將使用 boto3 更新 DynamoDb。 在這段代碼中, employee_id是自動生成的,但您必須提供last_namefirst_name 我正在使用if-else 如果屬性趨於增加,檢查也會增加。 我無法繼續使用 if 條件。 我該如何解決這個問題我應該做出哪些改變

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
    )

我想出但不起作用的代碼

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"
        )

您應該考慮分別存儲更新表達式和表達式值,然后將完整集傳遞到 Lambda 函數中。

這也將允許您針對每個參數進行驗證(可能將其分解為驗證函數以避免函數過大)。 通過這種方式,您可以同時支持必需參數和可選參數,然后在最后驗證更新表達式是否具有有效參數。

也許像下面這樣?

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
    )

這可以進一步分解以通過可以執行這些檢查的函數重用邏輯,如下所示。

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]

測試活動

{
  "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