3
我试图使用Spark将文本文件导出到Postgres数据库。我正在使用下面的一段代码来导出单个文本文件。我在同一个文件夹中有近200个文本文件,每个文本文件具有相同的结构。不幸的是,一年的价值不是我的输入文件的一部分,因此我很难编码它。使用Spark将文本文件导出到PostgreSQL - 自动化
我希望一次上传所有这些文件,但不知道该怎么做,有人有什么建议吗?
from pyspark.sql import SQLContext, Row
sqlContext = SQLContext(sc)
lines = sc.textFile("/aaaa/bbbb/DataFile/t-1870.txt")
splits = lines.map(lambda l: l.split(","))
raw_data = splits.map(lambda b: Row(name=b[0], gender=b[1],count=int(b[2]),year=int(1870)))
schemaBabies = sqlContext.createDataFrame(raw_data)
schemaBabies.registerTempTable("raw_data")
df = sqlContext.sql("select * from raw_data")
pgurl="jdbc:postgresql://localhost:5432/sparkling?user=XXXX&password=XXXX"
properties={"user":"XXXX","password":"XXXX","driver":"org.postgresql.Driver","mode":"append"}
df.write.jdbc(url = pgurl ,table = "EDW.raw_data",properties=properties)
我确实根据您的输入对我的代码进行了一些更改,我可以将所有200多个文本文件加载到数据库中。真的很感激你的帮助。 – ytasfeb15