首页 > 解决方案 > AWS DynamoDB ExclusiveStartKey 默认值

问题描述

我正在尝试对 DynamoDB 进行查询,如果LastEvaluatedKey返回 a(意味着查询超过 1 MB),我想进行其他查询,以便从表中获取所有需要的数据,使用LastEvaluatedKeyasExclusiveStartKey进行下一个查询。这是我现在的代码:

query_response = table.query(
    KeyConditionExpression=Key('brand').eq(brand)
)

pagination_key = None

if 'LastEvaluatedKey' in query_response:
    pagination_key = query_response['LastEvaluatedKey']

    while pagination_key:
        next_query_response = table.query(
            KeyConditionExpression=Key('brand').eq(brand),
            ExclusiveStartKey=pagination_key
        )

但是,我想通过将查询提取到一个方法中来重构这段代码,并将它作为参数传递给 pagination_key。为此,我必须能够为第一次调用设置ExclusiveStartKey为或其他默认值FalseNone但我没有找到任何关于此的内容,或者我必须能够将所有内容排除在外ExclusiveStartKey,但我也不知道该怎么做。

标签: pythonamazon-dynamodb

解决方案


使用关键字参数**kwargs它可能看起来像这样。另外,我之前设置了查询,并且ExclusiveStartKey每次只更新。

query = { "KeyConditionExpression": Key('brand').eq(brand) }


ExclusiveStartKey = None
while True:
    if ExclusiveStartKey is not None:
        query['ExclusiveStartKey'] = ExclusiveStartKey
    query_response = table.query(**query)

    if 'LastEvaluatedKey' in query_response:
        ExclusiveStartKey = query_response['LastEvaluatedKey']
    else:
        break

推荐阅读