[英]Simple example of retrieving 500 items from dynamodb using Python
尋找一個從dynamodb中檢索500個項目的簡單示例,從而最大限度地減少查詢次數。 我知道有一個“多功能”功能可以讓我把它分解成50個查詢的塊,但不知道如何做到這一點。
我從一個500鍵的列表開始。 我正在考慮編寫一個函數,它接受這個鍵列表,將其分解為“塊”,檢索值,將它們重新拼接在一起,然后返回500個鍵值對的字典。
或者有更好的方法嗎?
作為必然結果,我將如何“排序”之后的項目?
根據您的方案,有兩種方法可以有效地檢索您的500項。
hash_key
,使用range_key
query
方法與hash_key
range_keys
AZ或ZA進行排序 BatchGetItem
方法 在實際方面,由於您使用Python,我強烈建議使用Boto庫進行低級訪問或使用dynamodb-mapper庫進行更高級別的訪問(免責聲明:我是dynamodb-mapper的核心開發人員之一)。
遺憾的是,這些庫都沒有提供一種簡單的方法來包裝batch_get操作。 相反,有一個用於scan
和query
的生成器,它“假裝”您在一個查詢中獲得所有內容。
為了通過批量查詢獲得最佳結果,我建議使用此工作流程:
UnprocessedKeys
我假設你用一個hash_key
創建了一個表“MyTable”
import boto
# Helper function. This is more or less the code
# I added to devolop branch
def resubmit(batch, prev):
# Empty (re-use) the batch
del batch[:]
# The batch answer contains the list of
# unprocessed keys grouped by tables
if 'UnprocessedKeys' in prev:
unprocessed = res['UnprocessedKeys']
else:
return None
# Load the unprocessed keys
for table_name, table_req in unprocessed.iteritems():
table_keys = table_req['Keys']
table = batch.layer2.get_table(table_name)
keys = []
for key in table_keys:
h = key['HashKeyElement']
r = None
if 'RangeKeyElement' in key:
r = key['RangeKeyElement']
keys.append((h, r))
attributes_to_get = None
if 'AttributesToGet' in table_req:
attributes_to_get = table_req['AttributesToGet']
batch.add_batch(table, keys, attributes_to_get=attributes_to_get)
return batch.submit()
# Main
db = boto.connect_dynamodb()
table = db.get_table('MyTable')
batch = db.new_batch_list()
keys = range (100) # Get items from 0 to 99
batch.add_batch(table, keys)
res = batch.submit()
while res:
print res # Do some usefull work here
res = resubmit(batch, res)
# The END
編輯:
我在Boto develop分支中為BatchList
添加了一個resubmit()
函數 。 它大大簡化了工作流程:
BatchList
submit()
resubmit()
,只要它不返回None。 這應該在下一個版本中提供。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.