Spark 从 PostgreSQL 读取单列 table

Spark read single column from PostgreSQL table

问题

有没有办法从 (PostreSQL) 数据库 table 将特定列加载为 Spark DataFrame?

以下是我试过的方法。

预期行为:

下面的代码应该导致只有指定的列被存储在内存中,而不是整个table(table对我的集群来说太大了).

# make connection in order to get column names
conn = p2.connect(database=database, user=user, password=password, host=host, port="5432")
cursor = conn.cursor()
cursor.execute("SELECT column_name FROM information_schema.columns WHERE table_name = '%s'" % table)

for header in cursor:
    header = header[0]
    df = spark.read.jdbc('jdbc:postgresql://%s:5432/%s' % (host, database), table=table, properties=properties).select(str(header)).limit(10)
    # doing stuff with Dataframe containing this column's contents here before continuing to next column and loading that into memory
    df.show()

实际行为:

发生内存不足异常。我假设这是因为 Spark 试图加载整个 table 然后 select 一列,而不是仅仅加载 selected 列?或者它实际上只加载了该列,但是该列太大了;我将该列限制为只有 10 个值,所以不应该是这样吗?

2018-09-04 19:42:11 ERROR Utils:91 - uncaught error in thread spark-listener-group-appStatus, stopping SparkContext
java.lang.OutOfMemoryError: GC overhead limit exceeded

SQL 只有一列的查询可以在 jdbc 中使用,而不是 "table" 参数,请在此处找到一些详细信息: