使用日期时间过滤器表达式查询 dynamoDB - 操作数不正确

问题描述 投票:0回答:1

抱歉我是新手,ChatGPT 无法帮助我。

我尝试查询我的 dynamodb 以获取所有早于 5 分钟的项目。

我的物品存储为:

{
  "main_event_code": {
    "S": "1160"
  },
  "event_code": {
    "S": "9999"
  },
  "last_upload": {
    "S": "2024-05-10T04:09:29.614535Z"
  }
}

这是我正在运行的Python脚本:

    current_utc_time = datetime.now(timezone.utc)
    past_time = current_utc_time - timedelta(minutes=5)
    
    # Format both times as ISO 8601 strings
    current_utc_time_iso = current_utc_time.strftime('%Y-%m-%dT%H:%M:%SZ')
    past_time_iso = past_time.strftime('%Y-%m-%dT%H:%M:%SZ')

    # Print the current UTC time and the time minus 5 minutes
    print(f"Current UTC Time: {current_utc_time_iso}")
    print(f"Time 5 Minutes Ago: {past_time_iso}")

    try:
        # Scan the table with a filter for items older than 'past_time'
        response = table.scan(
            FilterExpression="last_upload < :past_time",
            ExpressionAttributeValues={":past_time": {"S": past_time_iso}}
        )

但是我尝试了又尝试,但我总是得到:

查询 DynamoDB 表时出错:调用 Scan 操作时发生错误 (ValidationException):无效的 FilterExpression:运算符或函数的操作数类型不正确;运算符或函数:<, operand type: M

但我知道过滤器表达式可以工作,因为使用 AWS CLI 我得到了返回的项目

aws dynamodb scan --table-name ingestion_queue --filter-expression "last_upload < :val" --expression-attribute-values '{":val":{"S":"2024-05-10T04:23:08Z"}}'
python amazon-dynamodb boto3
1个回答
0
投票

您的问题是因为您在高级客户端上使用低级语法

{'xx': {'S':....
(假设您的客户端名为
table
)。

你有2个选择:

  1. 针对当前请求使用低级客户端,而不是资源客户端。
  2. 使用高级语法:
    Attr('last_upload').lt(past_time_iso)

更多信息请参见这篇博客文章

© www.soinside.com 2019 - 2024. All rights reserved.