首页 > 解决方案 > 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 结构并替换他们提供的示例中的变量。

标签: pythonjsondatabaseamazon-web-servicesamazon-dynamodb

解决方案


您的 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 但我不确定这是否有效......


推荐阅读