我有一个流数据帧,我正在尝试将其写入数据库。有用于将rdd或df写入Postgres的文档。但是,我无法找到有关如何在结构化流中完成操作的示例或文档。
我已经阅读了文档https://spark.apache.org/docs/latest/structured-streaming-programming-guide.html#foreachbatch,但是我不明白我将在何处创建jdbc连接以及如何将其写入数据库。
def foreach_batch_function(df, epoch_id):
# what goes in here?
pass
view_counts_query = windowed_view_counts.writeStream \
.outputMode("append") \
.foreachBatch(foreach_batch_function)
.option("truncate", "false") \
.trigger(processingTime="5 seconds") \
.start() \
.awaitTermination()
此函数接收常规数据帧并写入postgres表
def postgres_sink(config, data_frame):
config.read('/src/config/config.ini')
dbname = config.get('dbauth', 'dbname')
dbuser = config.get('dbauth', 'user')
dbpass = config.get('dbauth', 'password')
dbhost = config.get('dbauth', 'host')
dbport = config.get('dbauth', 'port')
url = "jdbc:postgresql://"+dbhost+":"+dbport+"/"+dbname
properties = {
"driver": "org.postgresql.Driver",
"user": dbuser,
"password": dbpass
}
data_frame.write.jdbc(url=url, table="metrics", mode="append",
properties=properties)
答案 0 :(得分:2)
使用结构化流媒体如何完成Postgres摄取的示例
class PostgreSqlSink(url: String, user: String, pwd: String) extends org.apache.spark.sql.ForeachWriter[org.apache.spark.sql.Row] {
val driver = "org.postgresql.Driver"
var connection: java.sql.Connection = _
var statement: java.sql.PreparedStatement = _
val v_sql = "insert INTO Table (A,B,C) values ( ?, ?, ?)"
def open(partitionId: Long, version: Long): Boolean = {
Class.forName(driver)
connection = java.sql.DriverManager.getConnection(url, user, pwd)
connection.setAutoCommit(false)
statement = connection.prepareStatement(v_sql)
true
}
def process(value: org.apache.spark.sql.Row): Unit = {
// ignoring value(0) as this is address
statement.setString(1, value(1).toString)
statement.setString(2, value(2).toString)
statement.setString(3, value(3).toString)
statement.executeUpdate()
}
def close(errorOrNull: Throwable): Unit = {
connection.commit()
connection.close
}
}
val url = "jdbc:postgresql://XX.XX.XX.XX:5432/postgres"
val user = "abc"
val pw = "abc@123"
val jdbcWriter = new PostgreSqlSink(url,user,pw)
val writeData = pg_df.writeStream
.foreach(jdbcWriter)
.outputMode("Append")
.trigger(ProcessingTime("30 seconds"))
.option("checkpointLocation", "s3a://bucket/check")
.start()
writeData.awaitTermination
答案 1 :(得分:0)
除了您已经拥有的东西以外,这里实际上几乎没有什么可做的。 foreachBatch
takes a function (DataFrame, Int) => None
,因此您所需要的只是一个小型适配器,其他所有功能都可以正常工作:
def foreach_batch_for_config(config)
def _(df, epoch_id):
postgres_sink(config, df)
return _
view_counts_query = (windowed_view_counts
.writeStream
.outputMode("append")
.foreachBatch(foreach_batch_for_config(some_config))
...,
.start()
.awaitTermination())
尽管说实话,从一开始就传递ConfigParser
是一个奇怪的想法。您可以调整签名并对其进行初始化
def postgres_sink(data_frame, batch_id):
config = configparser.ConfigParser()
...
data_frame.write.jdbc(...)
,其余的保持原样。这样,您可以直接使用函数:
...
.foreachBatch(postgres_sink)
...