python dynamodb - 参数类型无效

python dynamodb - Invalid type for parameter

我正在通过 CDK 创建一个 dynamodb table。

    const table = new dynamodb.Table(this, "my-table", {
      tableName: StackConfiguration.tableName,
      partitionKey: { name: "file_id", type: dynamodb.AttributeType.STRING },
    });

    dynamoReplayTable.addGlobalSecondaryIndex({
      indexName: "processed",
      # ideally would like boolean here but doesn't seem to be an option
      partitionKey: { name: "processed", type: dynamodb.AttributeType.STRING },
    });

然后使用 boto 3,我将数据插入到 table 中,就像这样

    failedRecord = {
        "file_id": str(file_id),
        "processed": "false",
        "payload": str(payload),
        "headers": str(headers),
    }

    table.put_item(Item=failedRecord)

然后我有另一个读取项目的服务,然后处理,我想将作为全局二级索引的已处理字段更新为 true。

我现在有这个代码

    table.update_item(
        Key={"file_id": file_id}, AttributeUpdates={"processed": "true"},
    )

但这会导致以下错误

Parameter validation failed:
Invalid type for parameter AttributeUpdates.processed, value: true, type: <class 'str'>, valid types: <class 'dict'>

DynamoDB 以非常具体的方式处理数据类型,您可以找到更多信息 here and here

在您的情况下,问题出在更新命令的值 "true" 周围。使用类型可能很棘手,boto3 提供了 TypeSerializerTypeDeserializer,您可以使用它们来为您处理转换:

import boto3
from boto3.dynamodb.types import TypeSerializer

serializer = TypeSerializer()

my_single_value = "processed"

print(serializer.serialize(my_single_value))
# {'S': 'processed'}

my_dict_object = {
  "processed": "true"
}

print({k: serializer.serialize(v) for k, v in my_dict_object.items()})
# {'processed': {'S': 'true'}}

使用以下代码解决了这个问题

    table.update_item(
        Key={"file_id": file_id},
        UpdateExpression="SET processed_status = :processed",
        ExpressionAttributeValues={":processed": "true"},
    )