如何使用 Lambda 从 Amazon AWS 中提取和转换单个 dynamodb 元素

How to extract and cast individual dynamodb element from Amazon AWS using Lambda

我正在通过 MQTT 协议将温度数据从 Raspberry PI 保存到 Amazon DynamoDB。这是我的数据库的布局:

我设法设置 lambda 函数来读取每个新的数据库条目并将其作为 JSON 消息发送回 mqtt。所以它可以被用户阅读:

我想要实现的是在到达时只提取温度值。转换为整数类型并简单检查温度是否低于或高于阈值,并基于该检查将消息打开或关闭发送到 mqtt。然后 mqtt 特定主题将读取消息(打开或关闭)并将打开或关闭 LED(加热器模拟器)

所以我要求的是帮助从 dynamodb 中提取温度场。我希望我应该好好休息...

谢谢大家!

import boto3
import json

client = boto3.client('iot-data', region_name='eu-west-1')
dynamo = boto3.resource('dynamodb')
table = dynamo.Table('mqtt_table')


# Change topic, qos and payload
def lambda_handler(event, context):
    response = table.scan()
    body = json.dumps(response['Items'])
    response = client.publish(
        topic='mytopic/iot2',
        qos=1,
        payload=body

    )

如果您只想获取 temperature 字段的值,请尝试以下操作:

for item in response['Items']:
    temperature = float(item['temperature'])

这应该将温度的值存储在变量中。

--- 更新 03/05/2018 ---

如果您想在项目添加到 DynamoDB 后立即读取它 table,请创建一个 DynamoDB 触发器。可以找到文档 here。您的 lambda 函数代码应如下所示:

import json

def lambda_handler(event, context):
    print json.dumps(event, default=str)
    for record in event['Records']:
        temperature = record['dynamodb']['NewImage']['temperature']['S']
        # temperature variable contains the value of temperature of the item added to the DynamoDB table.
        print temperature
    # If you need to do something else, please do it here...
    return 'Completed'