我在 aws lambda 函数中编写了一个 python 程序,它将数据从 MQTT 客户端存储到 DynamoDB 表,但它没有按顺序存储,所以我想为我存储在 DynamoDB 表中的每个项目添加一个序列号,以便我可以将其过滤掉.
import boto3
def lambda_handler(event, context):
client = boto3.client('dynamodb')
response = client.put_item(
TableName = 'esp8266_v2',
Item = {
'timestamp': {'S': event['timestamp']},
'accurrent': {'N': str(event['accurrent'])}
}
)
return 0.
这就是我写的代码。它在表中存储时间戳值和对应的当前值。但我想在 oreder 中为这些值添加序列号
当前表格看起来像这样
时间戳 | 当前 |
---|---|
2023-08-23 22:00:41 | 8.65 |
2023-08-23 22:23:15 | 8.75 |
我想要这样的故事
时间戳 | 当前 | 序列号 |
---|---|---|
2023-08-23 22:00:41 | 8.65 | 1 |
2023-08-23 22:23:15 | 8.75 | 2 |
2023-08-23 22:03:58 | 8.25 | 3 |
来自 ESP8266 的 MQTT 数据
{
"时间戳": "2023-08-23 22:00:41", “当前”:8.65
}
我尝试使用此代码添加序列号,但它为所有项目提供相同的序列号,而不是每个序列号从 1,2,3...开始
import boto3
def lambda_handler(event, context):
client = boto3.client('dynamodb')
# Get the current number of items in the DynamoDB table
response = client.describe_table(TableName='esp8266_v2')
item_count = response['Table']['ItemCount']
# Calculate the next serial number
serial_number = item_count + 1
# Store the MQTT data with the serial number in DynamoDB
response = client.put_item(
TableName='esp8266_v2',
Item={
'serial_number': {'N': str(serial_number)},
'timestamp': {'S': event['timestamp']},
'accurrent': {'N': str(event['accurrent'])}
}
)
return {
'statusCode': 200,
'body': f'Serial number {serial_number} added successfully.'
}
这段代码的输出表
时间戳 | 当前 | 序列号 |
---|---|---|
2023-08-23 22:00:41 | 8.65 | 1 |
2023-08-23 22:23:15 | 8.75 | 1 |
2023-08-23 22:03:58 | 8.25 | 1 |