如何在DynamoDB表中插入地图?

6

我有以下代码行:

table.put_item( Item={'filename' : key, 'status' : {'M' : iocheckdict }})
iocheckdict 的结构如下:
{'A': 'One', 'C': 'Three', 'D': 'Four', 'B': 'Two', 'E': 'Five'}

那么,当我运行代码时,会出现以下错误:

An error occurred (ValidationException) when calling the PutItem operation: One or more parameter values were invalid: Type mismatch for key status expected: S actual: M

尽管我已经将数据类型指定为M,但为什么会出现这种情况?

PS:我的表中有两列filenamestatus


表的属性定义:

"AttributeDefinitions": [
    {
        "AttributeName": "filename",
        "AttributeType": "S"
    },
    {
        "AttributeName": "status",
        "AttributeType": "S"
    }
],

我知道status的类型是S,但我在创建表时没有找到映射类型。我找到的只有stringbinarynumber


根据 http://boto3.readthedocs.io/en/latest/reference/services/dynamodb.html#DynamoDB.Client.put_item ,您必须传递一个 M,例如 "M": {"Name": {"S": "Joe"}, "Age": {"N": "35"}},换句话说,dict 部分应该像 {"Name": {"S": "Joe"}, "Age": {"N": "35"}} - Emre Sevinç
@EmreSevinç 谢谢。问题已更新。 - Dawny33
一个表的键列永远不能是除了数字、字符串或二进制之外的任何其他类型。此外,在 DynamoDB 中创建表只需要键列而不需要其他列。Map 类型的数据只能作为非键列。 - omuthu
感谢EmreSevinç和@omuthu。我不知道这个。显然,status是我的二级键。所以,它不能接受映射数据类型。我尝试使用_put_item_动态创建一个新列,并且它成功了 :) - Dawny33
是的,每个记录可以有任意列。除非您的数据有一个单一文件名键对应多个状态,否则您可以仅使用文件名作为键列。请参见下面我的答案以获取更简便的插入数据方式。 - omuthu
显示剩余3条评论
2个回答

9
更简便地向DynamoDB插入数据
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table("table_name")

item={}
item['filename'] = key
item['status'] = {'A': 'One', 'C': 'Three', 'D': 'Four', 'B': 'Two', 'E': 'Five'}

table.put_item(Item=item)

0

我也被文档中关于数据类型的重点所困惑。 感谢@omuthu的回答,我意识到只需要传入字典对象即可。我认为对问题的一个更简洁的回答是通过剥离'M'(映射)附加级别来简化原始的put_item()调用,即:

table.put_item( Item={'filename':key, 'status':iocheckdict} )

或者作为一个工作示例:

import boto3

dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table("test")

key="test1235.txt"
iocheckdict = {'A': 'One', 'C': 'Three', 'D': 'Four', 'B': 'Two', 'E': 'Five'}

table.put_item( 
    Item={
        'filename': key, 
        'status':   iocheckdict 
    }
)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接