当前位置: 首页 > 知识库问答 >
问题:

如何编写一个pyspark-dataframe到redshift?

辛锦
2023-03-14

我正在尝试编写一个pyspark数据帧到Redshift,但它导致了错误:-

java.util.ServiceConfigurationError:org.apache.spark.sql.sources.DataSourceRister:Provider org.apache.spark.sql.avro.avroFileFormat无法实例化

原因:java.lang.nosuchmethoderror:org.apache.spark.sql.execution.datasources.fileformat.$init$(lorg/apache/spark/sql/execution/datasources/fileformat;)V

Spark版本:2.4.1

Spark-submit命令:Spark-submit--master local[*]--jars~/downloads/spark-avro2.12-2.4.0.jar,~/downloads/aws-java-sdk-1.7.4.jar,~/downloads/redshiftjdbc42-no-awssdk-1.2.20.1043.jar,~/downloads/hadoop-aws-2.7.3.jar,~/downloads/hadoop-common-2.7.3.jar--packages com.databricks:spark-redshift2.11:2.0.1,

from pyspark.sql import DataFrameReader
from pyspark.context import SparkContext
from pyspark.sql.session import SparkSession
from pyspark.sql import SQLContext
from pyspark.sql.functions import pandas_udf, PandasUDFType
from pyspark.sql.types import *

import sys
import os

pe_dl_dbname            = os.environ.get("REDSHIFT_DL_DBNAME")
pe_dl_host              = os.environ.get("REDSHIFT_DL_HOST")
pe_dl_port              = os.environ.get("REDSHIFT_DL_PORT")
pe_dl_user              = os.environ.get("REDSHIFT_DL_USER")
pe_dl_password          = os.environ.get("REDSHIFT_DL_PASSWORD")

s3_bucket_path = "s3-bucket-name/sub-folder/sub-sub-folder"
tempdir = "s3a://{}".format(s3_bucket_path)

driver = "com.databricks.spark.redshift"
sc = SparkContext.getOrCreate()
sqlContext = SQLContext(sc)
spark = SparkSession(sc)
spark.conf.set("spark.sql.execution.arrow.enabled", "true")

sc._jsc.hadoopConfiguration().set("fs.s3.impl","org.apache.hadoop.fs.s3native.NativeS3FileSystem")

datalake_jdbc_url = 'jdbc:redshift://{}:{}/{}?user={}&password={}'.format(pe_dl_host, pe_dl_port, pe_dl_dbname, pe_dl_user, pe_dl_password)

"""
The table is created in Redshift as follows:
create table adhoc_analytics.testing (name varchar(255), age integer);
"""
l = [('Alice', 1)]
df = spark.createDataFrame(l, ['name', 'age'])
df.show()
df.write \
  .format("com.databricks.spark.redshift") \
  .option("url", datalake_jdbc_url) \
  .option("dbtable", "adhoc_analytics.testing") \
  .option("tempdir", tempdir) \
  .option("tempformat", "CSV") \
  .save()

共有1个答案

姬飞昂
2023-03-14

Databricks Spark-Redshift不能与Spark 2.4.1版本一起使用,下面是我维护的使其与Spark 2.4.1版本一起使用的版本https://github.com/goibibo/Spark-Redshift

如何使用:

pyspark--包“com.github.goibibo:spark-redshift:v4.1.0”--存储库“https://jitpack.io”

 类似资料: