【问题标题】:Dynamodb query/scan using python boto3使用 python boto3 进行 Dynamodb 查询/扫描
【发布时间】:2020-11-20 21:13:32
【问题描述】:

我的 dynamodb 表将时间戳(在 YYYY-MM-DD HH:MN:SS 中)作为 PrimaryKey 列,将温度作为排序键,而在数据 {“湿度”:42 ,“位置”:“房间”,“温度”: “恒温器”:}

在 boto3 python 中,我需要根据时间戳(现在和 15 分钟前)进行扫描,如果差异(温度 - 恒温器)> 5 超过 10 次,则返回 thermostat-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

   
    

【问题讨论】:

  • 请展示你的作品
  • def lambda_handler(event, context): Fifth_min_ago = now - timedelta(seconds=900) now = now.strftime('%F %T') Fifth_min_ago = Fifth_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: thermonew = thermostatVal + 5 tosensor = '{"thermostat":'+ str( thermonew) + '}' print(tosensor) return elif response['Count']

标签: python amazon-dynamodb boto3


【解决方案1】:

如果timestamp 是排序键,您可以使用Query 请求扫描所有时间戳> now-15min 的项目。

但是,不幸的是,timestamp 是您的哈希键。您可以找到时间戳 > now-15min 的项目的唯一方法是通过 all 您的项目 Scan。这将花费您很多钱:您为每件扫描的商品支付亚马逊费用,不是在过滤后返回的每件商品。

另一个问题是 DynamoDB 过滤语法(查看FilterExpression 文档)实际上不允许在测试中进行加减运算。如果您总是想做“温度 - 恒温器”,您可以将其用作属性之一(因此您可以在其上执行FilterExpression),第二个属性将是“恒温器”,稍后您可以添加两个起来得到“温度”。

【讨论】:

  • 我正在使用以下... fe = Key('timeStamp').between(fifteen_min_ago,now); response = table.scan(FilterExpression=fe & Attr('temperature').lt(thermostatVal)) ... 如何使用 FilterExpression 进行温度 - 恒温器?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多