[英]Dynamodb query/scan using python boto3
我的 dynamodb 表有時間戳(在 YYYY-MM-DD HH:MN:SS 中)作為 PrimaryKey 列和溫度作為排序鍵,而在數據 {“濕度”:42,“位置”:“房間”,“溫度”:,“恆溫器“:}
在 boto3 python 中,我需要根據時間戳(現在和 15 分鍾前)進行掃描,條件是差異(溫度 - 恆溫器)> 5 超過 10 次,然后返回恆溫器 5,如果(溫度 - 恆溫器)< 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
請求來掃描所有時間戳 > now-15min 的項目。
但是,不幸的是, timestamp
是您的 hash 密鑰。 找到時間戳 > now-15min 的項目的唯一方法是Scan
所有項目。 這將花費您很多錢:您為每件掃描的商品支付亞馬遜費用,而不是過濾后返回的每件商品。
另一個問題是 DynamoDB 過濾語法(查看FilterExpression
文檔)實際上不允許在測試中進行加減運算。 如果您總是想做“溫度 - 恆溫器”,您可以將其用作屬性之一(因此您可以對其進行FilterExpression
),第二個屬性將是“恆溫器”,稍后您可以將兩者相加得到“溫度”。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.