[英]Dynamo DB scan query to obtain output file in JSON format
我對使用 boto3 的 Dynamo DB 很陌生。 我想:獲取 Dynamo DB 中所有行的掃描並將其以JSON
格式存儲在文件中,以進行額外的數據處理。
我目前正在使用下面顯示的腳本來獲取詳細信息(將涉及分頁):
from __future__ import print_function # Python 2/3 compatibility
import boto3
import json
import decimal
from boto3.dynamodb.conditions import Key, Attr
# Helper class to convert a DynamoDB item to JSON.
class DecimalEncoder(json.JSONEncoder):
def default(self, o):
if isinstance(o, decimal.Decimal):
if o % 1 > 0:
return float(o)
else:
return int(o)
return super(DecimalEncoder, self).default(o)
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('Movies')
#fe = Key('year').between(1951, 1964)
pe = "#yr, title, info.rating"
# Expression Attribute Names for Projection Expression only.
ean = { "#yr": "year", }
esk = None
response = table.scan(
# FilterExpression=fe,
ProjectionExpression=pe,
ExpressionAttributeNames=ean
)
for i in response['Items']:
print(json.dumps(i, cls=DecimalEncoder))
while 'LastEvaluatedKey' in response:
response = table.scan(
ProjectionExpression=pe,
# FilterExpression=fe,
ExpressionAttributeNames= ean,
ExclusiveStartKey=response['LastEvaluatedKey']
)
for i in response['Items']:
print(json.dumps(i, cls=DecimalEncoder),)
這給了我 5000 行的示例輸出:
{"info": {"rating": 6.5}, "year": 2004, "title": "The Polar Express"}
{"info": {"rating": 5.7}, "year": 2004, "title": "The Prince & Me"}
{"info": {"rating": 5.3}, "year": 2004, "title": "The Princess Diaries 2: Royal Engagement"}
{"info": {"rating": 6.3}, "year": 2004, "title": "The Punisher"}
{"info": {"rating": 6.8}, "year": 2004, "title": "The SpongeBob SquarePants Movie"}
我無法獲得所需格式的輸出(如下所示)。 我在這里期待一個文件。
[
{"info": {"rating": 6.5}, "year": 2004, "title": "The Polar Express"},
{"info": {"rating": 5.7}, "year": 2004, "title": "The Prince & Me"},
{"info": {"rating": 5.3}, "year": 2004, "title": "The Princess Diaries 2: Royal Engagement"},
{"info": {"rating": 6.3}, "year": 2004, "title": "The Punisher"},
{"info": {"rating": 6.8}, "year": 2004, "title": "The SpongeBob SquarePants Movie"}
]
任何人都可以向我提供一些有關如何進一步調查的提示或指示嗎?
response['Items'] 不是您要查找的列表嗎? Response 是一個包含列表的字典,它只能是一個子集,因此您需要根據需要迭代多個響應。
參考: https : //boto3.amazonaws.com/v1/documentation/api/latest/reference/services/dynamodb.html#DynamoDB.Client.scan
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.