如何解决使用AWS Glue时如何在Postgres中将字符串另存为JSONB类型
我正在寻找有关如何在postgresql中将字符串写为jsonb类型的解决方案。因此,DynamicFrame有一个包含json数据的字符串列。尝试保存到Postgres时
DataSink0 = glueContext.write_dynamic_frame.from_catalog(frame = Transform0,database = "cms",table_name = "cms_public_listings",transformation_ctx = "DataSink0")
我收到以下错误:
遇到错误:
An error occurred while calling o1623.pyWriteDynamicFrame.
: org.apache.spark.SparkException: Job aborted due to stage failure: Task 0 in stage 134.0 failed 4 times,most recent failure: Lost task 0.3 in stage 134.0 (TID 137,ip-172-31-27-18.ec2.internal,executor 24): java.sql.BatchUpdateException: Batch entry 0 INSERT INTO "public".listings ([REMOVED_COLUMNS]) VALUES ([REMOVED_VALUES]) was aborted: ERROR: column "schema" is of type jsonb but expression is of type character varying
Hint: You will need to rewrite or cast the expression.
Position: 207 Call getNextException to see other errors in the batch.
我无法更改架构来保存字符串,因此要么使用AWS Glue ETL,要么必须制作Python Shell Job。我希望找到一种将PySpark与AWS Glue结合使用的方法。
解决方法
我更喜欢使用原生 spark 数据帧,因为它允许我进行更多自定义。我可以使用 stringtype 属性将 json 字段从数据帧转换为表中的 jsonb 字段。对于这种情况,我的数据框有两个字段。
from pyspark import SparkConf
sc = SparkContext.getOrCreate(SparkConf())
spark = SparkSession(sc)
df = spark.read.format('csv') \
.option('delimiter','|') \
.option('header','True') \
.load('your_path')
##some transformation...
url = 'jdbc:postgresql://your_host:5432/your_databasename'
properties = {'user':'*****','password':'*****','driver': "org.postgresql.Driver",'stringtype':"unspecified"}
df.write.jdbc(url=url,table='your_tablename',mode='append',properties=properties)
在执行上述脚本之前,您应该在 postgresql 中创建表,因为属性 mode 设置为 append。如下:
create table your_tablename
(
my_json_field jsonb,another_field int
)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。