通过hiveContext在Spark Job中使用Hive功能

时间:2016-04-06 03:47:11

标签: apache-spark pyspark hiveql spark-dataframe hivecontext

我正在使用Hive 1.2和Spark 1.4.1。以下查询通过Hive CLI完美运行:

hive> select row_number() over (partition by one.id order by two.id) as sk,
two.id, two.name, one.name, current_date() 
from avant_source.one one 
inner join avant_source.two two 
on one.id = two.one_id;

但是当我尝试在pyspark工作中通过HiveContext使用它时,它给了我一个错误:

py4j.protocol.Py4JJavaError: An error occurred while calling o26.sql.
: java.lang.RuntimeException: Couldn't find function current_date

代码段:

from pyspark import HiveContext

conf = SparkConf().setAppName('DFtest')
sc = SparkContext(conf=conf)
sqlContext = HiveContext(sc)

df = sqlContext.sql("select row_number() over (partition by one.id order by two.id) as sk, two.id, two.name, one.name, current_date() from avant_source.one one inner join avant_source.two two on one.id = two.one_id")

df.show()

sc.stop()

有没有办法在pyspark获取当前日期或时间戳?我尝试导入日期,日期时间,但它总是抛出一个错误,说找不到函数。

我尝试在pyspark 1.5 Sandbox中的数据框中使用current_date,但后来我也遇到了不同的错误。

df = sqlContext.createDataFrame([(current_date,)],[‘d’])
df.select(date_sub(df.d,1).alias('d')).collect()

错误:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/opt/mapr/spark/spark-1.5.2/python/pyspark/sql/dataframe.py", line 769, in select
    jdf = self._jdf.select(self._jcols(*cols))
  File "/opt/mapr/spark/spark-1.5.2/python/lib/py4j-0.8.2.1-src.zip/py4j/java_gateway.py", line 538, in __call__
  File "/opt/mapr/spark/spark-1.5.2/python/pyspark/sql/utils.py", line 40, in deco
    raise AnalysisException(s.split(': ', 1)[1])
pyspark.sql.utils.AnalysisException: cannot resolve 'datesub(d,1)' due to data type mismatch: argument 1 requires date type, however, 'd' is of struct<> type.;

请告知。

1 个答案:

答案 0 :(得分:0)

对于我的场景,我使用了以下

import datetime 
now =  datetime.datetime.now()
df = df.withColumn('eff_start', lit(now.strftime("%Y-%m-%d")))

对于Hive函数无法正确使用HiveCon HiveContext的错误,这是一个集群问题,其中运行HiveServer2的其中一个节点由于内存问题而导致警报过多。这导致了这个问题。它在运行Spark 1.5和Hive 1.2的MapR Sandbox上成功测试