【问题标题】:dynamodb/python updateitem append item in nested mapdynamodb/python updateitem 在嵌套地图中追加项目
【发布时间】:2021-05-30 23:35:41
【问题描述】:

如何将项目附加到 dynamodb 中的现有地图 我想添加一组新的位置/名称/标签。

dynamodb 中的结构如下所示

{  
"user": "xyz",   
"itemdetails": [
    {
      "location": "67666",
      "name": "item1",
      "tags": [
        "k7866"
      ]
    },
    {
      "location": "45444",
      "name": "item12",
      "tags": [
        "ha23",
        "ju4532"
      ]
    }
}

我尝试了以下但得到了一个

"无效的UpdateExpression:运算符或的操作数类型不正确 功能;运算符:ADD,操作数类型:MAP"

response = table.update_item(
    Key={
        'user': "xyz",
    },
    UpdateExpression = 'ADD #itemdetails :newItems',
    ExpressionAttributeNames = {
      '#itemdetails' : 'ids'
    },
    ExpressionAttributeValues = {
      ':newItems' : {"name":name, 
         "location":location,
         "tags":tags
        }
    },
    ReturnValues="UPDATED_NEW"

【问题讨论】:

    标签: python python-3.x dictionary amazon-dynamodb


    【解决方案1】:

    我现在用

    解决了
     UpdateExpression = 'SET itemdetails = list_append(itemdetails, :newitem)',
            ExpressionAttributeValues={
                ":newitem": [
                        {
                            "name":"TEST", 
                            "location":"TEST",
                            "tags":tags
                        }
                ]
            },
            ReturnValues="UPDATED_NEW"
        )
    

    【讨论】:

      【解决方案2】:

      我是 Lucid-Dynamodb 的作者,它是 AWS DynamoDB 的极简包装器。使用这个python库可以轻松解决这个问题。

      参考:https://github.com/dineshsonachalam/Lucid-Dynamodb#8-add-an-attribute-to-the-list

      from LucidDynamodb.Operations import DynamoDb
      import os
      import logging
      logging.basicConfig(level=logging.INFO)
      
      AWS_ACCESS_KEY_ID = os.getenv("AWS_ACCESS_KEY_ID")
      AWS_SECRET_ACCESS_KEY = os.getenv("AWS_SECRET_ACCESS_KEY")
      
      table_schema = {
          "TableName": "test",
          "KeySchema": [
              {
                  "AttributeName": "user",
                  "KeyType": "HASH"
              }
          ],
          "AttributeDefinitions": [
              {
                  "AttributeName": "user",
                  "AttributeType": "S"
              }
           ],
          "GlobalSecondaryIndexes": [],
          "ProvisionedThroughput": {
              "ReadCapacityUnits": 1,
              "WriteCapacityUnits": 1
          }
      }
      
      
      if __name__ == "__main__":
          
          # 1. create a new table
          db = DynamoDb(region_name="us-east-1", 
                      aws_access_key_id=AWS_ACCESS_KEY_ID, 
                      aws_secret_access_key=AWS_SECRET_ACCESS_KEY)
                      
          table_creation_status = db.create_table(
                                          TableName=table_schema.get("TableName"),
                                          KeySchema=table_schema.get("KeySchema"),
                                          AttributeDefinitions=table_schema.get("AttributeDefinitions"),
                                          GlobalSecondaryIndexes=table_schema.get("GlobalSecondaryIndexes"),
                                          ProvisionedThroughput=table_schema.get("ProvisionedThroughput")
          )
          if(table_creation_status == True):
              logging.info("{} table created successfully".format(table_schema.get("TableName")))
          else:
              logging.error("{} table creation failed".format(table_schema.get("TableName")))
          
          # 2. Create a new item
          item_creation_status = db.create_item(
              TableName=table_schema.get("TableName"), 
              Item =  {
                  "user": "xyz",
                  "itemdetails": [{
                          "location": "67666",
                          "name": "item1",
                          "tags": [
                              "k7866"
                          ]
                      },
                      {
                          "location": "45444",
                          "name": "item12",
                          "tags": [
                              "ha23",
                              "ju4532"
                          ]
                      }
                  ]
              }
          )
          if(item_creation_status == True):
              logging.info("Item created successfully")
          else:
              logging.warning("Item creation failed")
              
          
          # 3. Add/Append an attribute to the list
          item_update_status = db.update_item(
              TableName=table_schema.get("TableName"), 
              Key={
                  "user": "xyz"
              },
              AttributesToUpdate={
                  "itemdetails": {
                          "location": "333",
                          "name": "item3",
                          "tags": [
                              "tag333"
                          ]
                      }
              },
              Operation="ADD_ATTRIBUTE_TO_LIST"
          )
          if(item_update_status == True):
              logging.info("Update is successful")
          else:
              logging.warning("Update failed")
      
          item = db.read_item(
              TableName=table_schema.get("TableName"), 
              Key={
                  "user": "xyz"
              })
          if(item != None):
              logging.info("Item: {}".format(item))
          else:
              logging.warning("Item doesn't exist")
      

      **输出:**

      dineshsonachalam@macbook Dynamodb-experiment % python test.py
      INFO:root:test table created successfully
      INFO:root:Item created successfully
      INFO:root:Update is successful
      INFO:root:Item: 
      
      {
          'itemdetails': [{
              'name': 'item1',
              'location': '67666',
              'tags': ['k7866']
          }, {
              'name': 'item12',
              'location': '45444',
              'tags': ['ha23', 'ju4532']
          }, {
              'name': 'item3',
              'location': '333',
              'tags': ['tag333']
          }],
          'user': 'xyz'
      }
      

      【讨论】:

        猜你喜欢
        • 2020-08-10
        • 2021-12-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多