繁体   English   中英

使用 python boto3 进行 Dynamodb 查询/扫描

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM