在ipython notebook中连接Postgres数据库的Pyspark

4
我已经阅读了之前的帖子,但我仍然无法确定为什么我无法将我的ipython笔记本连接到Postgres数据库。
我能够在ipython笔记本中启动pyspark,SparkContext被加载为'sc'。
我在我的.bash_profile中有以下内容以查找Postgres驱动程序:
export SPARK_CLASSPATH=/path/to/downloaded/jar

这是我在IPython笔记本中连接到数据库的步骤(基于this帖子):
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设置驱动程序,但是我收到了“没有这样的文件或目录”的错误。
这个blogpost也展示了如何连接到Postgres数据源,但以下内容也给我带来了“没有这样的目录”错误:
 ./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
3个回答

2

我不确定为什么上面的答案对我不起作用,但我想我也可以分享一下当我从jupyter notebook中运行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)

0

Apache Spark 在多次更新中已经改变了这个工作方式。查看我的设置,这是我在 .bashrc 中的设置(在 Mac 上称为 .bash_profile),所以你可以尝试一下:export SPARK_CLASSPATH=$SPARK_CLASSPATH:/absolute/path/to/your/driver.jar 编辑:我正在使用 Spark 1.6.1。

并且,像往常一样,请确保您使用一个新的 shell 或者 source 脚本,以便您拥有更新的环境变量(在运行 ipython notebook 之前,在您的 shell 中验证 echo $SPARK_CLASSPATH)。


什么是绝对路径?我获取了驱动器的真实路径并使用它。我改成了上面显示的方式,但问题仍然存在。 - cocanut
{btsdaf} - cocanut
1
我已经连接上了,等我有时间的时候会上传我的解决方案以便记录,但基本上,我认为这是因为spark_classpath已被弃用,所以你必须使用--driver-class-path。 - cocanut
@cocanut 通过绝对路径,我指的是不使用任何~快捷方式。我认为你做得很对。是的,这是我对Spark的抱怨之一:有许多已弃用的方法来完成所有操作。尽管被弃用,但SPARK_CLASSPATH对我仍然有效,但我使用的是1.6.1版本。 - sudo

0

我按照this帖子中的说明进行操作。对于我来说,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”设置,它也起作用了。正如在帖子的其他地方所述,这可能是因为SPARK_CLASSPATH已经被弃用,最好使用--driver-class-path。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接