我的dynamodb表的时间戳(在YYYY-MM-DD HH:MN:SS中)作为主键列,温度作为排序键,而数据{“湿度”:42,“位置”:“房间”,“温度”:“恒温器”:}
在boto3 python中,我需要根据时间戳(现在和15分钟前)扫描,条件是差值(温度-恒温器)>;5超过10次,然后返回恒温器-5和if(温度-恒温器)<;5超过10次,然后返回恒温器+5。。。下面是代码
import boto3
import math
import json
import time
import dateutil.tz
from datetime import datetime,timedelta
from dateutil import tz
from dateutil.tz import tzlocal
from boto3.dynamodb.conditions import Key, Attr
client = boto3.client('dynamodb')
dynamodb = boto3.resource('dynamodb')
def lambda_handler(event, context):
#table_name= "thermostat_dynamo"
table_name= "TableDynamo"
Primary_Column_Name = 'timestamp'
table = dynamodb.Table(table_name)
#key_param = "thermostat"
#thermostatVal = table.get_item(Key={key_param:event[key_param]}) ## get record from dynamodb for this sensor
thermostatVal= 77
south = dateutil.tz.gettz('Asia/Kolkata')
now = datetime.now(tz=south)
fifteen_min_ago = now - timedelta(seconds=900)
now = now.strftime('%F %T')
fifteen_min_ago = fifteen_min_ago.strftime('%F %T')
fe = Key('timeStamp').between(fifteen_min_ago,now);
response = table.scan(FilterExpression=fe & Attr('temperature').lt(thermostatVal))
if response['Count'] == 10:
#return thermostatVal+5
thermonew = thermostatVal + 5
tosensor = '{"thermostat":'+ str(thermonew) + '}'
print(tosensor)
#response = client.publish(topic="updatehomesensor", qos=1, payload=tosensor)
return
elif response['Count'] < 10:
print('{"thermostat":' + str(thermostatVal) + '}')
return
如果
timestamp
是一个排序键,那么可以使用Query
请求扫描所有带有时间戳的项目>;现在,15分钟然而,不幸的是,
timestamp
是您的哈希键。找到带有时间戳的项目的唯一方法>;现在-15分钟是通过所有您的物品Scan
。这将花费你很多钱:你为扫描的每个项目向亚马逊付款,而不是在过滤后返回的每个项目另一个问题是DynamoDB过滤语法(查看
FilterExpression
文档)实际上不允许将加法和减法作为测试的一部分。如果你总是想做“温度-恒温器”,你可以把它作为属性之一(这样你就可以对它做一个FilterExpression
),第二个属性是“恒温器”,然后你可以把这两个属性加起来得到“温度”相关问题 更多 >
编程相关推荐