【问题标题】:How do I append a list to my DynamoDB table using Python?如何使用 Python 将列表附加到我的 DynamoDB 表?
【发布时间】:2020-08-22 00:38:01
【问题描述】:

我有一个现有的 DynamoDB 表,我想编写一些 Python 代码来将属性(列表类型)附加到表中。这是我尝试过的:

users.put_item(

    Item={

        "new_attribute": []

    }

)

但这没有用。我在网上到处找,但找不到任何东西,我知道我一定错过了一些基本的东西。任何帮助将不胜感激。

【问题讨论】:

    标签: python python-3.x python-2.7 amazon-dynamodb amazon-dynamodb-local


    【解决方案1】:

    这是一个完整的例子

    ### 模拟列表的插入和更新 #创建表 导入 boto3 dynamodb = boto3.resource('dynamodb') 尝试: 表 = dynamodb.create_table( TableName='Test_list', KeySchema=[ { '属性名':'_id', 'KeyType': 'HASH' # 分区键 } ], 属性定义=[ { '属性名':'_id', '属性类型':'N' } ], 预置吞吐量={ 'ReadCapacityUnits':5, 'WriteCapacityUnits':5 } ) 除了 ClientError 作为 e: 如果 e.response['Error']['Code']: 打印(e.response['错误']['消息']) 打印(e.response) ## 用列表添加记录 table=dynamodb.Table('Test_list') ll=['一个','两个'] resp=table.put_item( 项目={ '_id': 1, “我的名单”:我 } ) #更新列表 new_ll=['三','四'] 响应 = table.update_item( 键={ '_id': 1 }, UpdateExpression="SET #l = list_append(#l, :vals)", 表达式属性名称={ "#l": '我的列表' }, 表达式属性值={ ":vals": new_ll } ) # 获取记录进行验证 resp=table.get_item(Key={'_id':1}) 响应 ['项目']

    你会看到输出:

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

    【讨论】:

      【解决方案2】:
      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': []
          }
      )
      

      【讨论】:

      • 我将代码粘贴到一个空白文件中,但收到此错误消息:botocore.exceptions.ClientError: An error occurred (ValidationException) when calling the UpdateItem operation: The provided key element does not match the schema
      猜你喜欢
      • 1970-01-01
      • 2019-11-27
      • 1970-01-01
      • 2021-11-13
      • 2017-05-01
      • 2018-10-09
      • 1970-01-01
      • 2019-09-02
      • 1970-01-01
      相关资源
      最近更新 更多