Skip to main content
 首页 » 编程设计

python之更改 dynamoDB 中列类型的最佳方法

2025年02月15日10lidabo

我有从不同服务/来源填充的 DynamoDB 表。该表具有下一个架构:

{ 
  "Id": 14782, 
  "ExtId": 1478240974, //pay attention it is Number 
  "Name": "name1" 
} 

有时,在服务开始工作后,我发现一项服务发送的数据格式不正确。看起来像:

{ 
  "Id": 14782, 
  "ExtId": "1478240974", //pay attention it is String 
  "Name": "name1" 
} 

DynamoDB 是 NoSQL 数据库,所以现在我有数百万难以查询或扫描的混合记录。我知道我的主要错误是错过了验证。

现在我必须抛出所有记录,如果它是不合适的类型 - 删除它并添加相同的数据但格式正确。是否可以用另一种优雅的方式来做?

请您参考如下方法:

所以这很容易。可以使用 attribute_type 方法。

首先,我添加了导入:

from boto3.dynamodb.conditions import Attr 
import boto3 

还有我的代码:

    attr = Attr('ExtId').attribute_type('S') 
    response = table.scan(FilterExpression = attr) 
    items = response['Items'] 
 
    while 'LastEvaluatedKey' in response: 
        response = table.scan(FilterExpression = attr, ExclusiveStartKey = response['LastEvaluatedKey']) 
        items.extend(response['Items']) 

可以在下一篇文章中找到更多条件定制 - DynamoDB Customization Reference