如何使用Python将列表附加到DynamoDB表中?

问题描述

我有一个现有的DynamoDB表,并且我想编写一些Python代码以将一个属性(类型为List)添加到表中。这是我尝试过的:

users.put_item(

    Item={

        "new_attribute": []

    }

)

但这没用。我在网上到处都是,但找不到任何东西,我知道我一定缺少一些基本的知识。任何帮助将不胜感激。

解决方法

import boto3

dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('<your-ddb-table-name>')

table.update_item(
    Key={
        'PK': '<pk>','SK': '<sk>'
    },UpdateExpression='SET new_attribute = :list',ExpressionAttributeValues={
        ':list': []
    }
)
,

这是一个可行的完整示例

    ### Simulating an Insert and Update to a List

    #Create Table
    import boto3
    dynamodb = boto3.resource('dynamodb')
    try:
        table = dynamodb.create_table(
                TableName='Test_list',KeySchema=[
                    {
                        'AttributeName': '_id','KeyType': 'HASH'  # Partition key
                    }
                ],AttributeDefinitions=[
                    {
                        'AttributeName': '_id','AttributeType': 'N'
                    }
                ],ProvisionedThroughput={
                    'ReadCapacityUnits': 5,'WriteCapacityUnits': 5
                }
            )

    except ClientError as e:
        if e.response['Error']['Code']:
            print(e.response['Error']['Message'])
        print( e.response)

    ## Add a record with a list
    table= dynamodb.Table('Test_list')
    ll=['one','two']
    resp=table.put_item(
    Item={
        '_id': 1,'mylist': ll
    }
    )

    #Update the list
    new_ll=['three','four']
    response = table.update_item(
        Key={
            '_id': 1
        },UpdateExpression="SET #l = list_append(#l,:vals)",ExpressionAttributeNames={
            "#l":  'mylist'
        },ExpressionAttributeValues={
            ":vals":  new_ll
        }
    )

    # fetch the record to verify
    resp=table.get_item(Key={'_id':1})
    resp['Item']


您将看到输出:

{'_id': Decimal('1'),'mylist': ['one','two','three','four']}