如何在 Amazon DynamoDB 中實作分頁?

1 分的閱讀內容
0

當我使用查詢或掃描操作從 Amazon DynamoDB 資料表擷取項目時,回應不會傳回完整的結果。

解決方法

在下列兩種情況下會發生這個問題:

  • 您的初始查詢或掃描操作在回應中包含 LastEvaluatedKey
  • 您沒有將此金鑰用作下一個請求執行後續操作的 ExclusiveStartKey

若要解決此問題,請為 DynamoDB 表格實作分頁。分頁是在先前的請求不完整時傳送後續請求以繼續的過程。DynamoDB 中的查詢或掃描操作可能會傳回不完整的結果,而且需要後續請求才能取得整個結果集。這是因為 DynamoDB 會對查詢或掃描操作的結果分頁,並在單一操作中傳回最多 1MB 的資料。資料上限是 DynamoDB 中的硬性限制。透過分頁,掃描和查詢操作的結果會分為 1 MB 或更小的資料頁面。

若要在 Amazon DynamoDB 中實作分頁,請使用內建分頁功能。執行類似下列範例的命令:

use DynamoDB.Paginator.Query.paginate

client = boto3.client("dynamodb")
paginator = client.get_paginator("scan")
params = {}

for page in paginator.paginate(params):
# do something

您也可以對結果進行分頁,並一次擷取一頁。若要查看結果是否包含 LastEvaluatedKey 元素,請檢查掃描或查詢操作的低階結果。若要取得剩餘結果,請使用具有相同參數的其他掃描或查詢操作。對於第二項操作,請使用 LastEvaluatedKey 作為 ExclusiveStartKey 參數。如果結果不包含 LastEvaluatedKey 值,則沒有要擷取的項目。

如需詳細資訊,請參閱分頁資料表查詢結果對結果分頁

若要使用 LastEvaluatedKey 在 Boto3 中實作分頁,請執行類似下列範例的命令:

from __future__ import print_function  # Python 2/3 compatibility
import boto3
from botocore.exceptions import ClientError

# Create Client
session = boto3.session.Session()
dynamoDbClient = session.client('dynamodb')

table_name = 'AmazonBins'

# Track number of Items read
item_count = 0

try:    
    # Get the first 1MB of data    
    response = dynamoDbClient.scan(
        TableName=table_name
    )

except ClientError as error:
    print("Something went wrong: ")
    print(error.response['ResponseMetadata'])

# Track number of Items read
item_count += len(response['Items'])

# Paginate returning up to 1MB of data for each iteration
while 'LastEvaluatedKey' in response:
    try:
        response = dynamoDbClient.scan(
            TableName=table_name,
            ExclusiveStartKey=response['LastEvaluatedKey']
        )
        # Track number of Items read
        item_count += len(response['Items'])

    except ClientError as error:
        print("Something went wrong: ")
        print(error.response['ResponseMetadata'])

print("Total number of items found: {}".format(item_count))
AWS 官方
AWS 官方已更新 8 個月前