pyspark 1.3.0将数据框保存到HIVE表中

时间:2017-01-20 11:32:31

标签: python hadoop pyspark

我正在使用spark 1.3.0(在python上)

我有DF:

DF.show(3)

ID             Date       Hour     TimeInCluster Cluster Xcluster Ycluster

25342438156 2012-11-30 15:00:00 26            T       130270   165620

25342438156 2012-11-30 16:00:00 86            D       136850   177070

25342438156 2012-11-30 17:00:00 35            D       136850   177070

我想把DF保存到不存在的hive表中

我该怎么做?

谢谢

我将我的代码更改为:

sqlContext = HiveContext(sc)

FinalDf.write().mode(SaveMode.Overwrite).saveAsTable("myDB.sixuserstablediary")

但我得到了那个错误

py4j.protocol.Py4JJavaError: An error occurred while calling o280.apply.
: org.apache.spark.sql.AnalysisException: Cannot resolve column name "write" among (IMSI, Date, Hour, TimeInCluster, Cluster, Xcluster, Ycluster);
        at org.apache.spark.sql.DataFrame$$anonfun$resolve$1.apply(DataFrame.scala:162)
        at org.apache.spark.sql.DataFrame$$anonfun$resolve$1.apply(DataFrame.scala:162)
        at scala.Option.getOrElse(Option.scala:120)
        at org.apache.spark.sql.DataFrame.resolve(DataFrame.scala:161)
        at org.apache.spark.sql.DataFrame.col(DataFrame.scala:436)
        at org.apache.spark.sql.DataFrame.apply(DataFrame.scala:426)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:497)
        at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:231)
        at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:379)
        at py4j.Gateway.invoke(Gateway.java:259)
        at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:133)
        at py4j.commands.CallCommand.execute(CallCommand.java:79)
        at py4j.GatewayConnection.run(GatewayConnection.java:207)
        at java.lang.Thread.run(Thread.java:745)

1 个答案:

答案 0 :(得分:1)

您需要使用Spark HiveContext

导入Spark HiveContex

from pyspark.sql import HiveContext
sqlContext = HiveContext(sc)

从数据框创建一个临时表,然后通过从临时表中选择数据插入到hive表中。

// Register the dataframe
   df.registerTempTable("tbl_tmp")

   sqlContext.sql("create table default.tbl_hive_data as select * from tbl_tmp")