DynamoDB 更新一个字段,该字段具有 JSON 作为值,integer/num-string 作为 python 中的键

DynamoDB update a field which has a JSON as value with integer/num-string as keys in python

我正在我的 dynamodb 中存储具有以下结构的项目 table。

Item = {"response": [
    {
        "answers": {
            "11-18": 0,
            "19-24": 0
        }
    }
]}

我想逐步更新 response[0].answers.11-18。 我的命令是:

table_resource.update_item(
        Key={
            'id': 123
        },
        UpdateExpression="set response[0].answers.11-18 = response[0].answers.11-18 + :inc",
        ExpressionAttributeValues={":inc": 1},
        ReturnValues="UPDATED_NEW",
)

我收到以下错误。

An error occurred (ValidationException) when calling the UpdateItem operation: Invalid UpdateExpression: Syntax error; token: "11", near: ".11-"

您的嵌套属性 11-18 以数字开头,因此您不能在更新表达式中使用它。

If an attribute name begins with a number or contains a space, a special character, or a reserved word, then you must use an expression attribute name to replace that attribute's name in the expression.

您可以使用占位符 ExpressionAttributeNames 解决此问题。