amazon-dynamodb - 在 dynamoDB 中更新或创建嵌套元素

标签 amazon-dynamodb boto3

我想更新或创建 DynamoDB 项目以获取下一个元素:

{
    "id": 156, 
    "date": 12323233.000,
    "countries": {
        "ua": 1,
        "ru": 2}
}

我使用 python 和 boto3。所以我可以检查是否字段 countries存在,如果不存在则添加。但这将意味着 2 个 DB 请求。
table.update_item(
    Key={
        'id': 156,
        'date': date,
    },
    UpdateExpression='SET countries = if_not_exists(countries, :countries)',
    ExpressionAttributeValues={
        ':countries': {},
    },
)

table.update_item(
    Key={
        'id': 156,
        'date': date,
    },
    UpdateExpression='ADD countries.#country :inc',
    ExpressionAttributeNames={"#country": country},  
    ExpressionAttributeValues={
        ':inc': 1
    },
)

有没有办法将这 2 个请求合二为一?

最佳答案

我最近不得不做这样的事情,花了一段时间才弄清楚。如果我的一组“完成”页面中不存在某个页面,我想增加一个计数。如果不是,它会递增并将页码添加到集合中。花了一段时间才意识到您可以“附加”到列表中,但必须“添加”到集合中。

try:
    res = dbt.update_item(
        Key={'pk': 'doc3', 'sk': 'na'},
        ReturnConsumedCapacity='INDEXES', ReturnValues='ALL_NEW',
        ExpressionAttributeNames={
            '#count': 'count',
            '#done': 'done',
        },
        ExpressionAttributeValues={
            ':1': 1,
            ':page': page,
            ':pagelist': set([page]),
        },
        ConditionExpression="(NOT contains(done, :page))",
        UpdateExpression="ADD #done :pagelist, #count :1",
    )
    print(f'rand int page={page} count={res["Attributes"]["count"]}'
          f' CU={res["ConsumedCapacity"]["Table"]}')
except ClientError as err:
    if err.response['Error']['Code'] == 'ConditionalCheckFailedException':
        print('Already got page=%s (%s)' % (page, err))
    else:
        raise

关于amazon-dynamodb - 在 dynamoDB 中更新或创建嵌套元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46979162/

相关文章:

amazon-web-services - 从 Lambda 代码调用 AWS boto 函数

python - 模拟 boto3 调用实际的 boto3

amazon-web-services - go and dynamo 从表中的字段和字段不为空/字段不为空的表中获取数据

node.js - 如何获取 aws-dynamoDB 中存在的所有字段?

amazon-web-services - DynamoDB 和 Lambda 的 Amazon IoT 规则问题

amazon-web-services - 如何使用 boto3 将文件上传到 Amazon Glacier Deep Archive

amazon-web-services - 如何通过 AWS SAM 模板创建具有自动缩放吞吐量的 DynamoDB 表

java - 如何确定 DynamoDB Java SDK 中的索引数据类型

amazon-web-services - 从 DynamoDB 中查找没有哈希和范围键的行并将其删除

python - botocore.exceptions.ConnectTimeoutError : Connect timeout on endpoint URL