如何使用spark.Read.jdbc读取不同Pyspark数据帧中的多个文件



我有一个代码可以将多个文件(>10(读取到Pyspark中的不同数据帧中。然而,我想使用for循环和引用变量或类似的东西来优化这段代码。我的代码如下:

Features_PM = (spark.read
.jdbc(url=jdbcUrl, table='Features_PM',
properties=connectionProperties))
Features_CM = (spark.read
.jdbc(url=jdbcUrl, table='Features_CM',
properties=connectionProperties))

我试过这样的东西,但没有用:

table_list = ['table1', 'table2','table3', 'table4']
for table in table_list:
jdbcDF = spark.read 
.format("jdbc") 
.option("url", "jdbc:postgresql:dbserver") 
.option("dbtable", "schema.{}".format(table)) 
.option("user", "username") 
.option("password", "password") 
.load()

以上片段的来源:https://community.cloudera.com/t5/Support-Questions/read-multiple-table-parallel-using-Spark/td-p/286498

如有任何帮助,我们将不胜感激。感谢

您可以使用以下代码来实现您的最终目标。您将获得一个数据帧字典,其中键是表名,值是适当的数据帧

def read_table(opts):
return spark.read.format("jdbc").options(**opts).load()
table_list = ['table1', 'table2','table3', 'table4']

table_df_dict = {table: read_table({"url":"jdbc:postgresql:dbserver",
"dbtable":"schema.{}".format(table),
"user": "username",
"password":"password"})
for table in table_list}

最新更新