DynamoDB更新计数器(或插入密钥)

met*_*eto 6 python amazon-web-services amazon-dynamodb

我有一个生成(some_key, some_value)对的函数,我想把它放在我的DynamoDB中.如果与主要的项目some_key是已经存在,我想添加some_valuevalue属性.否则我想创建这样的项目.按照文档中的示例,似乎函数if_not_exists应该按照我的意愿执行.我遇到了语法问题,因为我的代码返回错误:

>>>> table.update_item(
        Key={
            'key': my_key
        },
        UpdateExpression="set my_value = if_not_exist(my_value + :inc, :inc)",

        ExpressionAttributeValues={
            ':inc': my_increment,
        },
        ReturnValues="UPDATED_NEW"
    )

ClientError: An error occurred (ValidationException) when calling the UpdateItem operation: 
Invalid UpdateExpression: Syntax error; token: "+", near: "coocc + :val"
Run Code Online (Sandbox Code Playgroud)

Vor*_*Vor 14

对于这种类型的操作,您可以简单地使用ADD函数.来自文档:

ADD - 如果该属性尚不存在,则将指定的值添加到项目中.如果该属性确实存在,则ADD的行为取决于属性的数据类型

因此,通过使用,boto3.client()您可以执行以下操作:

client.update_item(
    TableName='MyTable',
    Key={'myhash': {'S': 'myvalue'}},
    UpdateExpression="ADD #counter :increment",
    ExpressionAttributeNames={'#counter': 'counter'},
    ExpressionAttributeValues={':increment': {'N': '1'}}
) 
Run Code Online (Sandbox Code Playgroud)

counter如果该字段不存在,则会创建该字段,如果该字段存在则会增加该字段.

  • 这绝对是最好的答案! (2认同)

Bor*_*rov 10

你可以这样做:

table.update_item(
    Key={
        'key': my_key
    },
    UpdateExpression="SET my_value = if_not_exists(my_value, :start) + :inc",

    ExpressionAttributeValues={
        ':inc': my_increment,
        ':start': 0,
    },
    ReturnValues="UPDATED_NEW"
)
Run Code Online (Sandbox Code Playgroud)

update_item遗嘱是否创建新项目或更新现有的.

UpdateExpression将检查是否my_value已存在并使用现有的my_value + :inc.

如果my_value不存在则将其:start用作初始值.