简体   繁体   English

DynamoDB 更新多个值

[英]DynamoDB Update Multiple values

I have the following table stored in DynamoDB:我在 DynamoDB 中存储了下表:

{
    "name" :"A",
    "videos": [
        {
            "playlistId" : "ABCD"
            "title" : "Hello, world!"
        }
     ]
}

I want to make it into the following:我想把它变成以下内容:

{
    "name" :"A",
    "videos": [
        {
            "playlistId" : "ABCD"
            "title" : "Hello, world!"
        },
        {
            "playlistId" : "EFGH"
            "title" : "Bye, world!"
        },
        {
            "playlistId" : "IJKL"
            "title" : "Good morning, world!"
        }
     ]
}

I tried to do it using DynamoDB Create operation, but it threw Duplicate Key error because all three video objects have the same primary key ("name").我尝试使用 DynamoDB Create 操作来执行此操作,但它引发了 Duplicate Key 错误,因为所有三个视频对象都具有相同的主键(“名称”)。

Now, I am trying to do so by updating the "videos", by appending to the list.现在,我试图通过附加到列表来更新“视频”来做到这一点。 When I do so, it throws Unsupported type error.当我这样做时,它会抛出不支持的类型错误。 Can someone nudge me in the right direction in this?有人可以在这方面向正确的方向推动我吗?

You have to use UpdateExpression update_item boto3 API. Below is the code I tried to insert an item:您必须使用UpdateExpression update_item boto3 API。下面是我尝试插入项目的代码:

import boto3
ddb_session = boto3.resource('dynamodb', region_name='us-east-1')
table = ddb_session.Table('test_table')
table.put_item(Item={
    'name': 'A',
    'videos': [
        {
            "playlistId": "ABCD",
            "title": "Hello, world!"
    }
]})

To update Item A the below code can be used:要更新项目A ,可以使用以下代码:

import boto3


ddb_session = boto3.resource('dynamodb', region_name='us-east-1')
table = ddb_session.Table('test_table')


table.update_item(
    Key={'name': 'A'},
    UpdateExpression='SET #VALUE = :value',
    ExpressionAttributeNames={
        '#VALUE': 'videos'
    },
    ExpressionAttributeValues={
        ':value': [
            {
                "playlistId": "ABCD",
                "title": "Hello, world!"
            },
            {
                "playlistId": "EFGH",
                "title": "Bye, world!"
            },
            {
                "playlistId": "IJKL",
                "title": "Good morning, world!"
            }
        ]
    },
)

Now let's see the output too.现在让我们也看看 output。 On put_item you will get something like below:put_item你会得到类似下面的东西:

在此处输入图像描述

On calling update_item you would get something like:在调用update_item你会得到类似的东西:

在此处输入图像描述

that is what expected in question.这就是预期的问题。 You can read more about UpdateExpression here您可以在此处阅读有关UpdateExpression的更多信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM