【问题标题】:Is there a way to efficiently fetch all the results from a medium sized DynamoDB?有没有办法有效地从中型 DynamoDB 中获取所有结果?
【发布时间】:2021-02-28 00:39:47
【问题描述】:

我在 python 中使用 boto3,但我相信问题和逻辑应该在所有语言中通用。

我知道table.scan() 理论上应该返回所有记录,但实际上它们的 scan() 结果大小限制为 1MB。建议基于 LastEvaluatedKey 创建一个 while 循环,但这也不会给我所有的结果(15200 而不是 16000),代码在这里:

dynamodb = boto3.resource('dynamodb', region_name='eu-west-2')
table = dynamodb.Table(dBTable)
response = table.scan()
print("item_count:", table.item_count)
print("response1:", response["Count"])

items=[]
while 'LastEvaluatedKey' in response and response['LastEvaluatedKey'] != "":  
    print("response:", response["Count"])
    items+=response["Items"]
    response = table.scan(ExclusiveStartKey=response['LastEvaluatedKey'])

如何可靠地获取所有记录?

【问题讨论】:

    标签: amazon-web-services aws-lambda amazon-dynamodb boto3 dynamodb-queries


    【解决方案1】:

    建议基于 LastEvaluatedKey 创建一个 while 循环,但这也不会给出所有结果(15200 而不是 16000)。

    你确定吗?我的猜测是你有其他事情发生。我在每天运行的生产代码的循环中使用 boto3 和 LastEvaludatedKey,并且从未遇到过没有返回所有行的情况 - 并不是说​​不可能,但我会首先确保您的代码是正确的。

    编辑,这段代码有效:

    import boto3
    
    from boto3.dynamodb.conditions import Key, Attr
    
    dynamodb = boto3.resource('dynamodb', region_name='us-east-1')
    table = dynamodb.Table('DeadLetterQueue')
    response = table.scan()
    print("item_count:", table.item_count)
    
    items=response["Items"]
    while 'LastEvaluatedKey' in response and response['LastEvaluatedKey'] != "":  
        response = table.scan(ExclusiveStartKey=response['LastEvaluatedKey'])
        items.extend(response["Items"])
    
    
    print (len(items))
    

    【讨论】:

    • 我在我的问题中添加了代码,你介意看一下吗?我在 lambda 上运行它——如果重要的话
    • 我已经为你添加了工作代码,与你的略有不同,但你应该能够适应它。
    • 谢谢,成功了!这完全是关于行的顺序
    【解决方案2】:

    您面临的问题与 DynamoDB 扫描操作无关。它与您的代码有关。最后一次扫描操作没有附加到 items 数组。

    以下是您的代码稍作修改 -

    dynamodb = boto3.resource('dynamodb', region_name='eu-west-2')
    table = dynamodb.Table(dBTable)
    response = table.scan()
    print("item_count:", table.item_count)
    print("response1:", response["Count"])
    
    items=response["Items"] // Changed HERE.
    while 'LastEvaluatedKey' in response and response['LastEvaluatedKey'] != "":  
        response = table.scan(ExclusiveStartKey=response['LastEvaluatedKey'])
        print("response:", response["Count"])
        items+=response["Items"] // Shifted this line HERE
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-07
      • 2012-12-23
      相关资源
      最近更新 更多