You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何以最简方式在DynamoDB中查询timestamp,避免使用GSI?

无需GSI提取DynamoDB中符合时间条件的数据

如果不想折腾GSI,最简的办法就是用**全表扫描(Scan)**配合过滤表达式,直接在扫描过程中筛选出timestamp晚于指定时间的数据。

代码实现

import boto3

# 简化初始化流程(你之前的代码重复创建了client和resource,这里优化下)
session = boto3.Session(profile_name="myprofile")
resource = session.resource("dynamodb", region_name="eu-central-1")
table = resource.Table("mytable")

# 执行扫描并过滤时间条件
response = table.scan(
    FilterExpression="timestamp > :cutoff_time",
    ExpressionAttributeValues={":cutoff_time": "2018-10-15 00:00:00"}
)

# 收集符合条件的数据
filtered_items = response['Items']

# 处理分页(当返回数据超过1MB时,需要继续扫描剩余数据)
while 'LastEvaluatedKey' in response:
    response = table.scan(
        FilterExpression="timestamp > :cutoff_time",
        ExpressionAttributeValues={":cutoff_time": "2018-10-15 00:00:00"},
        ExclusiveStartKey=response['LastEvaluatedKey']
    )
    filtered_items.extend(response['Items'])

# 输出结果
for item in filtered_items:
    print(item)

注意事项

  • 全表扫描会遍历表内所有数据,数据量大时性能拉胯,还会消耗更多读取容量(RCU),只适合小表或者临时查询的场景。
  • 你的timestamp是字符串格式,由于用了YYYY-MM-DD HH:MM:SS,fff这种符合字典序的格式,直接做字符串比较是有效的,能正确筛选时间先后。

内容的提问来源于stack exchange,提问作者John

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 08:45:31