本文介紹如何通過 Python SDK 範圍讀取Table Store中的資料。
前提條件
方法說明
def get_range(self, table_name, direction,
inclusive_start_primary_key,
exclusive_end_primary_key,
columns_to_get=None,
limit=None,
column_filter=None,
max_version=1,
time_range=None,
start_column=None,
end_column=None,
token=None,
transaction_id=None):範例程式碼
以下範例程式碼用於讀取 test_table 表中主索引值大於 row1 的資料。
try:
# 設定查詢起始主鍵
inclusive_start_primary_key = [('id', 'row1')]
# 設定查詢結束主鍵(返回結果不包含結束主鍵)
exclusive_end_primary_key = [('id', INF_MAX)]
# 調用 get_range 方法查詢資料
consumed, next_start_primary_key, row_list, next_token = client.get_range('test_table', Direction.FORWARD,
inclusive_start_primary_key, exclusive_end_primary_key)
# 返回結果處理
print('* Read CU Cost: %s' % consumed.read)
print('* Write CU Cost: %s' % consumed.write)
print('* Rows Data:')
for row in row_list:
print(row.primary_key, row.attribute_columns)
except Exception as e:
print("Range get failed with error: %s" % e)單次範圍掃描資料上限為 5000 行或者 4 MB,超出限制部分的資料將返回用於下一次讀取的起始主索引值,您可以參考以下代碼進行迭代查詢。
while True:
# 調用 get_range 方法查詢資料
consumed, next_start_primary_key, row_list, next_token = client.get_range('test_table', Direction.FORWARD,
inclusive_start_primary_key,
exclusive_end_primary_key)
# 返回結果處理
print('* Read CU Cost: %s' % consumed.read)
print('* Write CU Cost: %s' % consumed.write)
print('* Rows Count: %s' % len(row_list))
print('* Rows Data:')
for row in row_list:
print(row.primary_key, row.attribute_columns)
# 設定下一次讀取資料起始主鍵
if next_start_primary_key:
inclusive_start_primary_key = next_start_primary_key
else:
break您也可以在查詢資料時參考範例程式碼進行以下設定。
設定讀取的資料版本範圍,結果只返回版本範圍內的資料。
# 設定查詢的資料版本範圍為目前時間往前一天 time_range = (int(time.time() * 1000 - 86400 * 1000), int(time.time() * 1000)) consumed, next_start_primary_key, row_list, next_token = client.get_range('test_table', Direction.FORWARD, inclusive_start_primary_key, exclusive_end_primary_key, time_range= time_range)指定讀取的屬性列。
columns_to_get = ['col1'] # 調用 get_range 方法查詢資料 consumed, next_start_primary_key, row_list, next_token = client.get_range('test_table', Direction.FORWARD, inclusive_start_primary_key, exclusive_end_primary_key, columns_to_get)設定單次返回最大行數。
limit = 10 # 調用 get_range 方法查詢資料 consumed, next_start_primary_key, row_list, next_token = client.get_range('test_table', Direction.FORWARD, inclusive_start_primary_key, exclusive_end_primary_key, limit=limit)