简体   繁体   English

使用 Python 更新 DynamoDB 表中的 JSON 记录

[英]Update JSON Records in DynamoDB table using Python

I have a JSON record which looks like:我有一个 JSON 记录,如下所示:

 {'ip_address': data['src_ip'],
  'first_seen': data['timestamp'],
  'last_seen': data['timestamp']
                        }

The record gets stored in DynamoDB table with ip_address as the primary key.记录以ip_address作为主键存储在 DynamoDB 表中。

When the same IP appears again, I want to update the last seen value.当同样的 IP 再次出现时,我想更新最后看到的值。 I created a function with below lines:我用以下几行创建了一个 function:

def update_db(json_result):
    ddb_data = json.loads(json.dumps(json_result), parse_float=Decimal)
    database = boto3.resource('dynamodb', endpoint_url="https://dynamodb.us-west-2.amazonaws.com")
    table = database.Table('IPData')
    print("adding :", json_result)
    #db_add = table.put_item(Item = ddb_data)
    response = table.update_item(
                        Key = {
                            'ip_address': json_result['ip_address'] 
                        },
                        UpdateExpression="SET 'last_seen' = :s",
                        ExpressionAttributeValues = {
                                        ':s': json_result['last_seen']
                        },
                        ReturnValues="UPDATED_NEW"
                    )
    return response

This results into an error as:这会导致错误:

{
  "errorMessage": "An error occurred (ValidationException) when calling the UpdateItem operation: Invalid UpdateExpression: Syntax error; token: \"'\", near: \"SET 'last_seen\"",
  "errorType": "ClientError",

Not sure what is wrong in my syntax here.不确定我的语法有什么问题。 Can someone help me fix the issue.有人可以帮我解决这个问题。

See the doc for update expressions and a boto3 example here .请参阅文档以获取更新表达式此处boto3示例。

Your UpdateExpression should probably be (no single-quotes):您的UpdateExpression应该是(没有单引号):

                        UpdateExpression="SET last_seen = :s",

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

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