我正在尝试遍历我的 DynamoDB 表中的所有项目。(我知道这是一个低效的过程,但我这样做是为了构建一个索引表。)
我了解 DynamoDB 的 scan() 函数返回 1MB 或提供的限制中的较小者。为了弥补这一点,我编写了一个函数来查找“LastEvaluatedKey”结果并从 LastEvaluatedKey 开始重新查询以获取所有结果。
不幸的是,似乎每次我的函数循环时,整个数据库中的每一个键都会被扫描,很快就会耗尽我分配的读取单元。它非常慢。
这是我的代码:
def search(table, scan_filter=None, range_key=None,
attributes_to_get=None,
limit=None):
""" Scan a database for values and return
a dict.
"""
start_key = None
num_results = 0
total_results = []
loop_iterations = 0
request_limit = limit
while num_results < limit:
results = self.conn.layer1.scan(table_name=table,
attributes_to_get=attributes_to_get,
exclusive_start_key=start_key,
limit=request_limit)
num_results = num_results + len(results['Items'])
start_key = results['LastEvaluatedKey']
total_results = total_results + results['Items']
loop_iterations = loop_iterations + 1
request_limit = request_limit - results['Count']
print "Count: " + str(results['Count'])
print "Scanned Count: " + str(results['ScannedCount'])
print "Last Evaluated Key: " + str(results['LastEvaluatedKey']['HashKeyElement']['S'])
print "Capacity: " + str(results['ConsumedCapacityUnits'])
print "Loop Iterations: " + str(loop_iterations)
return total_results
调用函数:
db = DB()
results = db.search(table='media',limit=500,attributes_to_get=['id'])
我的输出:
Count: 96
Scanned Count: 96
Last Evaluated Key: kBR23QJNAwYZZxF4E3N1crQuaTwjIeFfjIv8NyimI9o
Capacity: 517.5
Loop Iterations: 1
Count: 109
Scanned Count: 109
Last Evaluated Key: ATcJFKfY62NIjTYY24Z95Bd7xgeA1PLXAw3gH0KvUjY
Capacity: 516.5
Loop Iterations: 2
Count: 104
Scanned Count: 104
Last Evaluated Key: Lm3nHyW1KMXtMXNtOSpAi654DSpdwV7dnzezAxApAJg
Capacity: 516.0
Loop Iterations: 3
Count: 104
Scanned Count: 104
Last Evaluated Key: iirRBTPv9xDcqUVOAbntrmYB0PDRmn5MCDxdA6Nlpds
Capacity: 513.0
Loop Iterations: 4
Count: 100
Scanned Count: 100
Last Evaluated Key: nBUc1LHlPPELGifGuTSqPNfBxF9umymKjCCp7A7XWXY
Capacity: 516.5
Loop Iterations: 5
这是预期的行为吗?或者,我做错了什么?