python - DynamoDB Python:创建项目并将其添加到现有表
问题描述
我正在尝试将项目添加到 DynamoDB 中的现有表中,但是,我不断收到错误消息
缺少项目中的关键湿度
运行程序时。原始 JSON 数据在这里我创建项目的代码如下。
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 网站上提供的步骤 1创建类似的 JSON 结构并替换他们提供的示例中的变量。
解决方案
您的 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"
}
}
)
如果您希望这些值也存在于 machinevals 中,您可以随时在其中复制它们,但您的哈希和范围键需要位于根目录中。
您也可以尝试将您的哈希和范围键定义为 machinevals:humidity 和 machinevals:pressure 但我不确定这是否有效......
推荐阅读
- javascript - 在本地构建 vis-timeline 时出现 NPM 对等依赖问题
- google-cloud-platform - 为什么我的 GCloud 日志中的时间戳被截断为秒?
- reactjs - 试图保留原始数组(克隆,反应)
- javascript - 有没有办法访问谷歌浏览器的打印属性
- pyqtgraph - 如何 pyqtgraph 图例动作分组?
- javascript - 单击 javascript 相关按钮打开相关菜单
- python - 如何检查模块并确保我的模块安装正确?IDLE 找不到数学模块
- vim - 如何水平拆分 Neovim 拼写建议窗口?
- javascript - 如何将 react-native 道具从功能组件传递到类组件
- amazon-web-services - 使用同一账户的不同组织中的 AWS 访问环境