如何使用boto3更新dynamodb中一个项的几个属性

2024-04-29 06:30:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从dynamoDB中的一个表中更新一个项的几个属性。我的代码是用Python 3编写的。每次尝试时,我都会收到几个与更新表达式及其编写方式相关的错误。我查看了AWS站点中的文档和示例,但在一个与AttributeUpdates相关的步骤中感到困惑。

这是Node.js中创建的表的索引(我不能以任何方式修改它):

const Pages = dynamodb.define('Page', {
  hashKey : 'idPages',
  timestamps : true,//creates 2 string variables "createdAt" & "updatedAt"
  schema : {
    idPages : dynamodb.types.uuid(),//assigns one unique ID it is a string also
    url: Joi.string(),
    var1InTable: Joi.string(),//want to update this
    idSite: Joi.string(),
    var2InTable: Joi.array().allow(null)//want to update this
  },
  indexes: [
    {
      hashKey: 'idSite',
      rangeKey: 'url',
      name: 'UrlIndex',
      type : 'global'
    }
  ]
});

要更新的变量有两种,字符串和字符串列表:

dynamodb = boto3.resource('dynamodb', region_name='us-east-1')
tb_pages=dynamodb.Table('pages')
idPages="exampleID123"#hash key 
url="www.example.com"#range key
var1String="example string"
var2StrList=["Example","String","List"]
var3NewString="new string variable"

所以我在亚马逊上查看了这个例子,并遵循了它的结构:

        response=tb_pages.update_item(
            Key={
                    'idPages':item['idPages'],
                    'url':item['url']
                    },
            UpdateExpression="SET var1InTable= :var1, var2InTable= :var2,var3InTable= :var3",
            AttributeUpdates={
                    ':var1': var1String,
                    ':var2': var2StrList,
                    ':var3': var3NewString
                    },
            ReturnValues="UPDATED_NEW"

                )

对于AttributeUpdates中的所有变量,我得到了以下错误:

Invalid type for parameter AttributeUpdates.:var1, value: example string, type: <class 'str'>, valid types: <class 'dict'>

所以我遵循AWS boto3 documentation并用字典替换变量,字典中变量类型的代码是键,变量是值。

        response=tb_pages.update_item(
            Key={
                    'idPages':item['idPages'],
                    'url':item['url']
                    },
            UpdateExpression="SET var1InTable= :var1, var2InTable= :var2,var3InTable= :var3",
            AttributeUpdates={
                    ':var1': {"S":var1String},
                    ':var2': {"L":var2StrList},
                    ':var3': {"S":var3NewString},
                    },
            ReturnValues="UPDATED_NEW"

                )

并得到以下错误:

ParamValidationError: Parameter validation failed:
Unknown parameter in AttributeUpdates.:var1: "S", must be one of: Value, Action
Unknown parameter in AttributeUpdates.:var2: "L", must be one of: Value, Action
Unknown parameter in AttributeUpdates.:var3: "S", must be one of: Value, Action

我再次检查了文档,但对在哪里放置操作以及应该使用哪个操作感到困惑。

注意:我可以将字符串列表更改为字符串集,或者将它们合并到一个字符串中以简化操作,因为我不知道哪种python对象与Node.js中定义的Joi.array().allow(null)对象兼容。


Tags: 字符串urlstringparameterupdatepagesitemdynamodb
1条回答
网友
1楼 · 发布于 2024-04-29 06:30:43

经过多次尝试和阅读Dynamodb API documentation之后,我发现PutItem方法:

Creates a new item, or replaces an old item with a new item. If an item that has the same primary key as the new item already exists in the specified table, the new item completely replaces the existing item.

这可能不是最优的,但是通过使用具有相同键和值的putItem,可以替换整个项,在这种情况下

        tb_pages.put_item(
            Item={
                    'idPages':item['idPages'],#hash key
                    'url':item['url'],#range key
                    'var1InTable':var1String,
                    'var2InTable':var2StrList,
                    'var3InTable':var3NewString,
                    'otherAttributeToKeep':item['otherAttributeToKeep']#see the note
                    }
            )

注意:不要忘记再次传递项中的所有属性,因为此方法将重写项,否则它们将被覆盖并被删除。

编辑:

上的代码的问题是,我使用AttributeUpdate而不是ExpressionAttributeValues,一旦我更改了它,并且在正常工作的代码中将“url”作为键(因为url是一个保留字)

response=tb_pages.update_item(
    Key={
            'idPages':item['idPages'],
            'urlz':item['urlz']
            },
    UpdateExpression="SET var1InTable= :var1, var2InTable= :var2,var3InTable= :var3",
    ExpressionAttributeValues={
            ':var1': var1String,
            ':var2': var2StrList,
            ':var3': var3NewString
            },
    ReturnValues="UPDATED_NEW"

        )

相关问题 更多 >