我正在尝试将项目添加到DynamoDB中的现有表中,但是,我不断收到错误消息
缺少项目中的关键湿度
在运行程序时。原始JSON数据为here,下面是我创建项目的代码。
from __future__ import print_function # Python 2/3 compatibility
import boto3
import json
import decimal
# Helper class to convert a DynamoDB item to JSON.
class DecimalEncoder(json.JSONEncoder):
def default(self, o):
if isinstance(o, decimal.Decimal):
if abs(o) % 1 > 0:
return float(o)
else:
return int(o)
return super(DecimalEncoder, self).default(o)
dynamodb = boto3.resource('dynamodb', region_name='us-east-1', endpoint_url="https://dynamodb.us-east-1.amazonaws.com")
table = dynamodb.Table('Machines')
machinekey = 1
city = "Miami"
state = "Florida"
response = table.put_item(
Item={
'machinekey': machinekey,
'city': city,
'state': state,
'machinevals': {
'machineid': 1,
'date': "01/03/2019",
'humidity': 25,
'pressure': 105
}
}
)
print("PutItem succeeded:")
print(json.dumps(response, indent=4, cls=DecimalEncoder))
我创建表的代码如下。
from __future__ import print_function # Python 2/3 compatibility
import boto3
dynamodb = boto3.resource('dynamodb', region_name='us-east-1', endpoint_url="https://dynamodb.us-east-1.amazonaws.com")
table = dynamodb.create_table(
TableName='Machines',
KeySchema=[
{
'AttributeName': 'humidity',
'KeyType': 'HASH' #Sort key, not partition (HASH)
},
{
'AttributeName': 'pressure',
'KeyType': 'RANGE' #Sort key
}
],
AttributeDefinitions=[
{
'AttributeName': 'humidity',
'AttributeType': 'N'
},
{
'AttributeName': 'pressure',
'AttributeType': 'N'
},
]
ProvisionedThroughput={
'ReadCapacityUnits': 10,
'WriteCapacityUnits': 10
}
)
print("Table status:", table.table_status)
我一直遵循AWS's website上提供的步骤1,方法是创建类似的JSON结构并替换其提供的示例中的变量。
答案 0 :(得分:0)
您的Range和Hash键必须位于Item结构的根目录中...
response = table.put_item(
Item={
'machinekey': machinekey,
'city': city,
'state': state,
'humidity': 25,
'pressure': 105
'machinevals': {
'machineid': 1,
'date': "01/03/2019"
}
}
)
如果您希望这些值也包含在machineval中,则可以始终在其中复制它们,但是您的hash和range键必须位于根中。
您也可以尝试将哈希键和范围键定义为machinevals:湿度和machinevals:压力,但是我不确定这是否可行...