DynamoDB上将值附加到list属性

DynamoDB上将值附加到list属性

本文介绍了如何在AWS DynamoDB上将值附加到list属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将DynamoDB用作K-V数据库(因为没有太多数据,我认为这很好),并且'V'的一部分是列表类型(大约10个元素).有一些会话可以为其添加新值,而我无法在1个请求中找到实现此目的的方法.我所做的就是这样:

I'm using DynamoDB as an K-V db (cause there's not much data, I think that's fine) , and part of 'V' is list type (about 10 elements). There's some session to append a new value to it, and I cannot find a way to do this in 1 request. What I did is like this:

item = self.list_table.get_item(**{'k': 'some_key'})
item['v'].append('some_value')
item.partial_save()

我先请求服务器,然后在修改值后将其保存.那不是原子的,看起来很丑.有什么办法可以在一个请求中做到这一点吗?

I request the server first and save it after modified the value. That's not atomic and looks ugly. Is there any way to do this in one request?

推荐答案

以下代码应适用于boto3:

The following code should work with boto3:

table = get_dynamodb_resource().Table("table_name")
result = table.update_item(
    Key={
        'hash_key': hash_key,
        'range_key': range_key
    },
    UpdateExpression="SET some_attr = list_append(some_attr, :i)",
    ExpressionAttributeValues={
        ':i': [some_value],
    },
    ReturnValues="UPDATED_NEW"
)
if result['ResponseMetadata']['HTTPStatusCode'] == 200 and 'Attributes' in result:
    return result['Attributes']['some_attr']

这里的get_dynamodb_resource方法就是:

The get_dynamodb_resource method here is just:

def get_dynamodb_resource():
    return boto3.resource(
            'dynamodb',
            region_name=os.environ['AWS_DYNAMO_REGION'],
            endpoint_url=os.environ['AWS_DYNAMO_ENDPOINT'],
            aws_secret_access_key=os.environ['AWS_SECRET_ACCESS_KEY'],
            aws_access_key_id=os.environ['AWS_ACCESS_KEY_ID'])

这篇关于如何在AWS DynamoDB上将值附加到list属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 04:16