AWS 胶水转换

时间:2021-01-24 03:46:47

标签: python amazon-web-services amazon-s3 aws-glue

尝试从 s3 存储桶读取 Input.csv 文件,获取不同的值(并进行一些其他转换),然后写入 target.csv 文件,但在尝试将数据写入 s3 存储桶中的 Target.csv 时遇到问题。< /p>

代码如下:

import sys
from awsglue.utils import getResolvedOptions
from pyspark.context import SparkContext
from awsglue.context import GlueContext
from awsglue.dynamicframe import DynamicFrame
from awsglue.job import Job

glueContext = GlueContext(SparkContext.getOrCreate())

dfnew = glueContext.create_dynamic_frame_from_options("s3", {'paths': ["s3://bucket_name/Input.csv"] }, format="csv" )

dfMod = dfnew.select_fields(["Col2","Col3"]).toDF().distinct()

dnFrame  = DynamicFrame.fromDF(dfMod, glueContext, "test_nest")

datasink = glueContext.write_dynamic_frame.from_options(frame = dnFrame, connection_type = "s3",connection_options = {"path": "s3://bucket_name/Target.csv"}, format = "csv", transformation_ctx ="datasink") 

这是 Input.csv 中的数据:

Col1    Col2    Col3
1       1       -30.4
2       2       -30.5
3       3        6.70
4       4        5.89
5       4        6.89
6       4        6.70
7       4        5.89
8       4        5.89

错误:

val dfmod = dfnew.select_fields(["Col2","Col3"]).toDF().distinct().show() ^ SyntaxError: invalid syntax During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/opt/amazon/bin/runscript.py", line 92, in <module>
while "runpy.py" in new_stack.tb_frame.f_code.co_filename: AttributeError: 'NoneType' object has no attribute 'tb_frame'

我理解的原因是我使用的是 create_dynamic_frame_from_options 而不是 from_catalog 但是如何在使用 from_options 时获得所需的功能(因为我的格式是 s3 中的 csv)?。

IAM(胶水服务政策):

{
"Version": "2012-10-17",
"Statement": [
    {
        "Effect": "Allow",
        "Action": [
            "s3:GetObject",
            "s3:PutObject"
        ],
        "Resource": [
            "arn:aws:s3:::bucket_Name/Output/**/**/*"
        ]
    }
    ]
}

S3 存储桶政策:

{
"Version": "2012-10-17",
"Id": "Policy***",
"Statement": [
    {
        "Sid": "Stmt1***",
        "Effect": "Allow",
        "Principal": {
            "AWS": "arn:aws:iam::account_number:root"
        },
        "Action": "s3:*",
        "Resource": "arn:aws:s3:::bucket_name"
    }
    ]
}

请帮忙

1 个答案:

答案 0 :(得分:0)

语法错误在线

val dfMod = dfnew.select_fields(["Col2","Col3"]).toDF().distinct().show()

可以按如下方式更正,我们不需要 valshow() 它只会返回一个数据帧,我们在传递给 write_dynamic_frame 之前将其转换为 DynamicFrame 还需要顶部的导入语句from awsglue.dynamicframe import DynamicFrame

dfMod = dfnew.select_fields("Col2","Col3").toDF().distinct()
dnFrame  = DynamicFrame.fromDF(dfMod, glueContext, "test_nest")