PutItem AWS DynamoDB 的无效类型错误

sat*_*eri 2 python amazon-web-services amazon-dynamodb boto3

我们有一个带有分区键和排序键的 DynamoDB 表。两个键都是数字类型。我正在尝试使用 boto3 DynamoDB 客户端的 PutItem API 插入项目。我收到以下错误;

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\satis\Anaconda3\envs\py369\lib\site-packages\botocore\client.py", line 316, in _api_call
    return self._make_api_call(operation_name, kwargs)
  File "C:\Users\satis\Anaconda3\envs\py369\lib\site-packages\botocore\client.py", line 599, in _make_api_call
    api_params, operation_model, context=request_context)
  File "C:\Users\satis\Anaconda3\envs\py369\lib\site-packages\botocore\client.py", line 647, in _convert_to_request_dict
    api_params, operation_model)
  File "C:\Users\satis\Anaconda3\envs\py369\lib\site-packages\botocore\validate.py", line 297, in serialize_to_request
    raise ParamValidationError(report=report.generate_report())
botocore.exceptions.ParamValidationError: Parameter validation failed:
Invalid type for parameter Item.doc_id.N, value: 1234, type: <class 'int'>, valid types: <class 'str'>
Invalid type for parameter Item.passage_id.N, value: 1, type: <class 'int'>, valid types: <class 'str'>
Run Code Online (Sandbox Code Playgroud)

该错误没有意义,因为我插入的排序键的值是一个整数,并且与 dynamodb 的 Number 类型匹配。该错误明确指出值类型是整数,但所需类型是字符串。不确定我在这里缺少什么。

以下是我试图插入的数据;

{'doc_id': {'N': 1234}, 'passage_id': {'N': 1}, 'text': {'S': 'some text to insert'}, 'urls': {'S': '[]'}, 'html': {'S': '<p>this is para</p>'}}
Run Code Online (Sandbox Code Playgroud)

以下是我用来插入字典的代码;

import boto3
dynamodb_client=boto3.client('dynamodb',region_name='region_name')
dynamodb_client.put_item(TableName='table_name',Item=data)
Run Code Online (Sandbox Code Playgroud)

重申一下,这两个关键即。doc_id 和passage_id 是dynamodb 中的数字类型

感谢帮助。

小智 5

即使它是一个数字,您仍然需要输入一个字符串值。“N”关键字将其标识为数字。

"PutRequest": { 
    "Item": { 
        "string" : { 
            "B": blob,
            ...
            "N": "string",
            "NS": [ "string" ],
            "NULL": boolean,
            "S": "string",
            "SS": [ "string" ]
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

您可以BatchWriteItem在这里参考官方文档:https : //docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_BatchWriteItem.html

在您的情况下,您需要将文档 ID“1234”指定为字符串,“N”(数字)作为数据类型。