0

我遇到問題,試圖使用Python和Boto3將我的JSON文件加載到AWS dynamoDB中,當此文件具有子級json時。如何使用Boto3將一個子級JSON文件加載到DynamoDB中?

的exaple我有這樣的代碼波紋管:

from __future__ import print_function # Python 2/3 compatibility 
import boto3 

dynamodb = boto3.resource('dynamodb', region_name='sa-east-1', aws_access_key_id='AWS ACCESS KEY', aws_secret_access_key='AWS SECRET KEY') 
table = dynamodb.create_table(
    TableName='Movies', 
    KeySchema=[ 
     { 
      'AttributeName': 'year', 
      'KeyType': 'HASH' #Partition key 
     }, 
     { 
      'AttributeName': 'title', 
      'KeyType': 'RANGE' #Sort key 
     } 
    ], 
    AttributeDefinitions=[ 
     { 
      'AttributeName': 'year', 
      'AttributeType': 'N' 
     }, 
     { 
      'AttributeName': 'title', 
      'AttributeType': 'S' 
     }, 

    ], 
    ProvisionedThroughput={ 
     'ReadCapacityUnits': 10, 
     'WriteCapacityUnits': 10 
    } 
) 

print("Table status:", table.table_status) 

在這個佈局我在AWS dynamoDB創建一個表,但僅限於JSON在一個層面上的結構,如:

[ 
    { 
     "year": 2013, 
     "title": "Rush" 
    } 
] 

但如果我想把一個JSON文件與sublevel?我如何用Boto3創建這張桌子?以及如何輸入文件?像這樣:

[ 
    { 
     "year": 2013, 
     "title": "Rush", 
     "info": { 
      "directors": ["Ron Howard"], 
      "release_date": "2013-09-02T00:00:00Z", 
      "rating": 8.3, 
      "genres": [ 
       "Action", 
       "Biography", 
       "Drama", 
       "Sport" 
      ], 
      "image_url": "http://ia.media-imdb.com/images/M/MV5BMTQyMDE0MTY0OV5BMl5BanBnXkFtZTcwMjI[email protected]@._V1_SX400_.jpg", 
      "plot": "A re-creation of the merciless 1970s rivalry between Formula One rivals James Hunt and Niki Lauda.", 
      "rank": 2, 
      "running_time_secs": 7380, 
      "actors": [ 
       "Daniel Bruhl", 
       "Chris Hemsworth", 
       "Olivia Wilde" 
      ] 
     } 
    } 
] 

我讀Boto3文檔並在互聯網上搜索了一些教程,但我找不到如何做到這一點。它應該很簡單,我知道我必須有辦法做到這一點,但我還沒有得到它。有人給我一些小費?

回答

0

其實我做了一個簡單的概念錯誤。對於DynamoDB,當您創建表時,您不需要聲明表的每個屬性。在這個階段,你只需要說出誰是分區鍵和分配鍵(如果有的話)。如果您輸入的項目具有更多屬性,您可以在put_item()函數上聲明,如:

from __future__ import print_function # Python 2/3 compatibility 
import boto3 
import json 
import decimal 

dynamodb = boto3.resource('dynamodb', region_name='sa-east-1', aws_access_key_id='AWS ACCESS KEY', aws_secret_access_key='AWS SECRET KEY') 

table = dynamodb.Table('Movies') 

title = "The Big New Movie" 
year = 2015 

response = table.put_item(
    Item={ 
     'year': year, 
     'title': title, 
     'info': { 
      'plot':"Nothing happens at all.", 
      'rating': decimal.Decimal(0) 
     } 
    } 
) 
0

使用你上面的例子,我想你可以簡單地使用table.update_item()方法。

key = {'year': '2013'},{'title': 'Rush'} 
attribute_name = 'info' 
attribute_value = {} # build your info as a dictionary 
attribute_value['directors'] = ['Ron Howard'] 
... 

response = table.update_item(
    Key = key, 
    UpdateExpression="SET " + attribute_name + " = :val", 
    ExpressionAttributeValues={':val': attribute_value}, 
    ReturnValues="UPDATED_NEW" 
) 
相關問題