Pyspark 连接到 ipython 笔记本中的 Postgres 数据库

Pyspark connection to Postgres database in ipython notebook

我已经阅读了之前的 post,但我仍然无法确定为什么我无法将我的 ipython 笔记本连接到 Postgres 数据库。

我能够在 ipython notebook 中启动 pyspark,SparkContext 加载为 'sc'。

我的 .bash_profile 中有以下内容用于查找 Postgres 驱动程序:

export SPARK_CLASSPATH=/path/to/downloaded/jar

这是我在 ipython 笔记本中连接数据库的操作(基于 this post):

from pyspark.sql import DataFrameReader as dfr
sqlContext = SQLContext(sc)

table= 'some query'
url = 'postgresql://localhost:5432/dbname'
properties = {'user': 'username', 'password': 'password'}

df = dfr(sqlContext).jdbc(
url='jdbc:%s' % url, table=table, properties=properties
)

错误:

Py4JJavaError: An error occurred while calling o156.jdbc.
: java.SQL.SQLException: No suitable driver.

我知道找到我下载的驱动程序时出错,但我不明白为什么当我在我的 .bash_profile 中添加它的路径时会出现此错误。

我也尝试通过 pyspark --jars 设置驱动程序,但出现 "no such file or directory" 错误。

这个 blogpost 也显示了如何连接到 Postgres 数据源,但是下面也给我一个 "no such directory" 错误:

 ./bin/spark-shell --packages org.postgresql:postgresql:42.1.4

附加信息:

spark version: 2.2.0
python version: 3.6
java: 1.8.0_25
postgres driver: 42.1.4

他们已经多次更改了 Apache Spark 中的工作方式。查看我的设置,这就是我的 .bashrc(在 Mac 上又名 .bash_profile),因此您可以尝试一下:export SPARK_CLASSPATH=$SPARK_CLASSPATH:/absolute/path/to/your/driver.jar 编辑:我使用的是 Spark 1.6。 1.

而且,一如既往,请确保您使用新的 shell 或源脚本,以便您拥有更新的 envvar(在 shell 之前使用 echo $SPARK_CLASSPATH 验证 运行 ipython notebook).

我遵循了 post 中的指示。 SparkContext 已经为我设置为 sc,所以我所要做的就是从我的 .bash_profile 中删除 SPARK_CLASSPATH 设置,并在我的 ipython 笔记本中使用以下内容:

import os

os.environ['PYSPARK_SUBMIT_ARGS'] = '--driver-class-path /path/to/postgresql-42.1.4.jar --jars /path/to/postgresql-42.1.4.jar pyspark-shell'

我也为属性添加了一个 'driver' 设置,它起作用了。正如本 post 中其他地方所述,这可能是因为 SPARK_CLASSPATH 已被弃用,最好使用 --driver-class-path.

我不确定为什么上面的答案对我不起作用,但我想我也可以分享当 运行 来自 jupyter 笔记本的 pyspark 时对我有用的东西(Spark 2.3.1 - Python 3.6.3):

from pyspark.sql import SparkSession
spark = SparkSession.builder.config('spark.driver.extraClassPath', '/path/to/postgresql.jar').getOrCreate()
url = 'jdbc:postgresql://host/dbname'
properties = {'user': 'username', 'password': 'pwd'}
df = spark.read.jdbc(url=url, table='tablename', properties=properties)