使用Python和AWS Lambda将具有嵌套结构的Pandas Dataframe 写入DynamoDB

cgvd09ve  于 2022-11-20  发布在  Python
关注(0)|答案(1)|浏览(113)

我正在尝试将Pandas Dataframe 写入DynamoDB表。此帧具有嵌套对象

{
  "PK": {
    "S": "2"
  },
  "SK": {
    "S": "INFO"
  },
  "001": {
    "M": {
      "New_Some": {
        "N": "6"
      },
      "New_Some1": {
        "N": "2"
      },
      "New_Some2": {
        "N": "1"
      },
      "New_Some3": {
        "N": "1"
      }
    }
  },
  "status": {
    "S": "New"
  },
  "ModelVals": {
    "L": [
      {
        "M": {
          "Models": {
            "L": [
              {
                "S": "ABC123"
              }
            ]
          },
          "class": {
            "S": "XYZ222"
          }
        }
      }
    ]
  },

我的Pandas数据框列包含如下列表和字典-

column1- ["mfg_nom", "mfg_nom", "mfg_nom", "mfg_nom"]
column2 - ["ZZY", "ZZY", "XYZ", "XYZ"]
column3 - ["1", "2", "2", "1"]

and 

column4 - {"New_Some": "0.000"}
column5 - {"New_Some1": "636.000"}
column6 - {}
column7 - {"Insta": 7, "Other": 7}

pandas Dataframe 包含多个嵌套列表和字典。我如何创建此行插入到dynamoDB中。到目前为止,我已经尝试了以下方法,但它只适用于字符串而不是数组

df = wr.s3.read_parquet(path=s3_path, 
                            dataset=dataset,
                            path_suffix = path_suffix).isna()    

with table.batch_writer() as batch:
        for index, row in df.iterrows():
            print(row.to_json())
            batch.put_item(json.loads(row.to_json(), parse_float=Decimal))

获取错误,如-

"An error occurred (ValidationException) when calling the BatchWriteItem operation: The provided key element does not match the schema",
np8igboo

np8igboo1#

我的建议是使用AWS Glue而不是Lambda,Lambda有一个内置的DynamoDB连接器,允许您从S3读取并直接写入DynamoDB。
https://docs.aws.amazon.com/glue/latest/dg/aws-glue-programming-etl-connect.html#aws-glue-programming-etl-connect-dynamodb
但是,如果您必须使用Lambda,则可以使用awswrangler for DynamoDB:
https://aws-sdk-pandas.readthedocs.io/en/stable/stubs/awswrangler.dynamodb.put_df.html

相关问题