使用Boto3 API调用从DynamoDB读取数据。

0

【以下的问题经过翻译处理】 我目前正在尝试从我的DynamoDB数据库中分析数据,重点是查询当前和过去的日期。然而,我在使用AWS Web App时遇到了一些问题。具体来说,当我将日期设置为主键时,数据是可见的,但在尝试扫描它时,数据没有出现。

此外,我还尝试使用Boto3 API,但输出显示了一个不正确的“最后评估关键字”为20230318,扫描计数为12279,这不是准确的。下面是扫描表的部分代码: import boto3 import csv from datetime import datetime, timedelta from boto3.dynamodb.conditions import Attr

Initialize the DynamoDB client

dynamodb = boto3.resource('dynamodb', region_name='us-east-2')

Replace 'your_table_name' with the name of your DynamoDB table

table = dynamodb.Table('table_name')

Get the current day timestamp

current_day = "20230405" previous_day = "20230404" # datetime.now(timezone.utc).date().strftime("%Y%m%d") #today = datetime.now() #current_day = today.strftime('%Y%m%d') #previous_day = (today - timedelta(days=1)).strftime('%Y%m%d')

Scan the table

response_current_day = table.scan( ProjectionExpression='ip_address, pk, c2_name, #counter', ExpressionAttributeNames={ '#counter': 'counter', }, FilterExpression=Attr('pk').eq(current_day) ) 请求输出:

{'Items': [], 'Count': 0, 'ScannedCount': 12279, 'LastEvaluatedKey': {'pk': '20230318', 'sk': 'redacted'}, 'ResponseMetadata': {'RequestId': 'redacted', 'HTTPStatusCode': 200, 'HTTPHeaders': {'server': 'Server', 'date': 'Wed, 05 Apr 2023 21:14:11 GMT', 'content-type': 'application/x-amz-json-1.0', 'content-length': '126', 'connection': 'keep-alive', 'x-amzn-requestid': 'REDACTED', 'x-amz-crc32': '3416724477'}, 'RetryAttempts': 0}}

profile picture
专家
已提问 8 个月前118 查看次数
1 回答
0

【以下的回答经过翻译处理】 如果分区键是日期,我会首先尝试理解为什么要进行“扫描”。如果你的数据看起来像上面的表格,并且想要匹配日期“20230318”上的所有项,那么你应该使用Query API调用,这意味着你不必读取整个表格,只需要选择与日期匹配的部分。

response_current_day = table.query(
    ProjectionExpression='ip_address, pk, c2_name, #counter',
    ExpressionAttributeNames={
        '#counter': 'counter',
    },
    KeyConditionExpression=Key('pk').eq(current_day)
)
profile picture
专家
已回答 8 个月前

您未登录。 登录 发布回答。

一个好的回答可以清楚地解答问题和提供建设性反馈,并能促进提问者的职业发展。

回答问题的准则