【问题标题】:How to load a sublevel JSON file into DynamoDB using Boto3?如何使用 Boto3 将子级 JSON 文件加载到 DynamoDB?
【发布时间】:2017-12-07 02:20:05
【问题描述】:

我在尝试使用 Python 和 Boto3 将我的 JSON 文件加载到 AWS dynamoDB 时遇到问题,但该文件具有子级 json。

例如,我有以下代码:

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 文件呢?我如何用 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/MV5BMTQyMDE0MTY0OV5BMl5BanBnXkFtZTcwMjI2OTI0OQ@@._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 Docs 并在互联网上搜索了一些教程,但我找不到如何做到这一点。它应该很简单,我知道我必须有办法做到这一点,但我还不能得到它。有人给我一些建议吗?

【问题讨论】:

    标签: python python-2.7 amazon-web-services amazon-dynamodb boto3


    【解决方案1】:

    使用上面的示例,我认为您可以简单地使用 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"
    )
    

    【讨论】:

      【解决方案2】:

      其实我犯了一个简单的概念错误。对于 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)
              }
          }
      )
      

      【讨论】:

        【解决方案3】:

        如果你这样加载,它会处理嵌套的 JSON 结构,当你读出来的​​时候,你可以解析 JSON 并读取 JSON 中需要的属性

        import boto3
        import json
        
        dynamodbclient=boto3.resource('dynamodb')
        sample_table = dynamodbclient.Table('ec2metadata')
        
        with open('/samplepath/spotec2interruptionevent.json', 'r') as myfile:
            data=myfile.read()
        
        # parse file
        obj = json.loads(data)
        
        #instance_id and cluster_id is the Key in dynamodb table 
        
            response=sample_table.put_item(
                                      Item={
                                          'instance_id': instanceId,
                                          'cluster_id': clusterId,
                                          'event':obj
        
                                      }
                                      )
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2019-06-06
          • 1970-01-01
          • 1970-01-01
          • 2021-04-06
          • 2021-06-23
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多