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" 
) 
相关问题