Spark sql注册的临时表不能在sqlContext.read()中使用



我有以下代码

Map<String, String> props = getDbConnectionProps();
props.put("dbtable", sql);
props.put("fetchSize", "100000");
props.put("partitionColumn", "col1");
props.put("lowerBound", "25");
props.put("upperBound", "100");
props.put("numPartitions", "10");
String sql = "..."
DataFrame df = sqlContext.read().format("jdbc").options(props).load();
df.registerTempTable("myTable");
df.cache();
Map<String, String> props = getDbConnectionProps();
props.put("dbtable", sql2);
props.put("fetchSize", "100000");
props.put("partitionColumn", "col1");
props.put("lowerBound", "25");
props.put("upperBound", "100");
props.put("numPartitions", "10");
String sql2 = "... inner join myTable on ...."   // Note here the sql2 use the temp table
DataFrame df2 = sqlContext.read().format("jdbc").options(props).load();

然而,我在下面遇到了一个错误

java.sql.SQLSyntaxErrorException: Table 'myDbSchema.myTable' doesn't exist

所以注册的临时表不能在sqlContext.read((中使用?我知道我可以使用sqlContext.sql(sql2)来获得使用临时表的结果。但是,如何用sqlContext.sql((的方式设置分区信息等属性呢?

谢谢。

很明显,您使用.format("jdbc")读取数据库,而df.registerTempTable("myTable");是加载数据后内存中存在的一个火花实体/数据。

DataFrame df2 = sqlContext.read().format("jdbc").options(props).load();

错误声明myDbSchema.myTable不存在,因为您传递的查询字符串正在数据库上操作。

sql2 = "... inner join myTable on ...."
java.sql.SQLSyntaxErrorException: Table 'myDbSchema.myTable' doesn't exist

对于您的问题:我知道我可以使用sqlContext.sql(sql2(来获得使用临时表的结果。但是,如何用sqlContext.sql((的方式设置分区信息等属性呢?

当两个数据集太大而无法由数据库连接/处理时,解决方案1是最佳的,反之亦然。请找到下面的伪代码。

解决方案1:在DF2中加载第二个表的数据,然后在spark中执行联接。

DataFrame df = sqlContext.read().format("jdbc").options(props).load();
DataFrame df2 = sqlContext.read().format("jdbc").options(props2).load();
spark.conf.set("spark.sql.shuffle.partitions",10)
DataFrame joindf = df.join(df2, joinCondition, "inner")

解决方案2:通过连接两个表在数据库中创建一个视图/表,例如此处的joinedview,并通过读取并行度加载数据=>分区成火花。

In Database:
create view joinedview as 
select * from table inner join myTable 
on (joincondition)
In Spark:
Map<String, String> props = getDbConnectionProps();
props.put("dbtable", joinedview);
props.put("fetchSize", "100000");
props.put("partitionColumn", "col1");
props.put("lowerBound", "25");
props.put("upperBound", "100");
props.put("numPartitions", "10");
DataFrame df2 = sqlContext.read().format("jdbc").options(props).load();

我不确定如何在没有sql的情况下完成它,但我认为错误可能会出现,因为您正在尝试读取表"myTable";使用格式("jdbc"(,而不是根据临时存储的设置。

最新更新