为了账号安全,请及时绑定邮箱和手机立即绑定

如何向 Dynamodb 地图添加新密钥而不覆盖现有密钥?

如何向 Dynamodb 地图添加新密钥而不覆盖现有密钥?

萧十郎 2023-09-05 19:45:07
根据我的代码,首先,我向地图添加一个新字典,它会成功更新到我的地图。但是,当我向地图添加另一个字典时,地图中的现有键会被覆盖。def update_item(table_name, id, new_company):    table = dynamodb.Table(table_name)    result = table.update_item(        Key={            'id': id        },        UpdateExpression="SET  company = :company",        ExpressionAttributeValues={            ':company': new_company        },        ReturnValues="ALL_NEW"    )    print(result)if __name__ == '__main__':    company_1 = {        "Facebook" : {            "CEO" : "Mark"        }    }    update_item('companies', 1, company_1)    company_2 = {        "Twitter": {            "CEO": "Jack"        }    }    update_item('companies', 1, company_2)我的输出:我的 Dynamodb 表中可用的项目{    'company': {        'Twitter': {            'CEO': 'Jack'        }    },    'id': Decimal('1'),    'industry': 'industry'}预期输出:{    'company': {        'Facebook': {            'CEO': 'Mark'        }        'Twitter': {            'CEO': 'Jack'        }    },    'id': Decimal('1'),    'industry': 'industry'}当我向地图添加新字典时,如何避免覆盖现有字典?我是 DynamoDB 的新手,任何建议都会有帮助。
查看完整描述

2 回答

?
阿晨1998

TA贡献2037条经验 获得超6个赞

问题出在你的UpdateExpression. 您每次都将 map 的值设置company为新值:

SET  company = :company

但听起来您想向地图附加一个新值company

查看完整回答
反对 回复 2023-09-05
?
慕姐8265434

TA贡献1813条经验 获得超2个赞

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

参考: https: //github.com/dineshsonachalam/Lucid-Dynamodb

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": "company",

    "KeySchema": [

        {

            "AttributeName": "id",

            "KeyType": "HASH"

        }

    ],

    "AttributeDefinitions": [

        {

            "AttributeName": "id",

            "AttributeType": "N"

        }

     ],

    "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=  {

                'company': {

                    'Facebook': {

                        'CEO': 'Mark'

                    }

                },

                'id': 1,

                'industry': 'internet'

        }

    )

    if(item_creation_status == True):

        logging.info("Item created successfully")

    else:

        logging.warning("Item creation failed")

    

    # 3. Add a new attribute in a item

    item_update_status = db.update_item(

        TableName=table_schema.get("TableName"), 

        Key={

            'id': 1

        },

        AttributesToUpdate={

            'company.Twitter': {

                'CEO': 'Jack'

            }

        }

    )

    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={

            'id': 1

        })

    if(item != None):

        logging.info("Item: {}".format(item))

    else:

        logging.warning("Item doesn't exist")

输出:

dineshsonachalam@macbook Dynamodb-experiment % python test.py

INFO:root:company table created successfully

INFO:root:Item created successfully

INFO:root:Update is successful

INFO:root:Item: 

{

    'company': {

        'Facebook': {

            'CEO': 'Mark'

        },

        'Twitter': {

            'CEO': 'Jack'

        }

    },

    'id': Decimal('1'),

    'industry': 'internet'

}


查看完整回答
反对 回复 2023-09-05
?
红颜莎娜

TA贡献1842条经验 获得超12个赞

您只需在#name 处添加一个地图条目即可。


def update_item(table_name, id, new_company):

    table = dynamodb.Table(table_name)

    name = list(new_company)[0]

    result = table.update_item(

        Key={

            'id': id

        },

        UpdateExpression="SET  company.#name = :company",

        ExpressionAttributeNames={"#name": name},

        ExpressionAttributeValues={

            ':company': new_company[name]

        },

        ReturnValues="ALL_NEW"

    )

    print(result)


输出:我的 Dynamodb 中可用的项目


{

    'company': {

        'Facebook': {

            'CEO': 'Mark'

        },

        'Twitter': {

            'CEO': 'Jack'

        }

    },

    'id': Decimal('1'),

    'industry': 'internet'

}

https://img1.sycdn.imooc.com//64f715180001b91203190212.jpghttps://img1.sycdn.imooc.com//64f7151b0001b91203190212.jpg

查看完整回答
反对 回复 2023-09-05
  • 2 回答
  • 0 关注
  • 199 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信