如何在spark中使用transform python udf执行hql脚本?

时间:2017-09-14 07:27:57

标签: python hadoop hive pyspark pyspark-sql

我是新手,通过POC激发和学习。作为这个POC的一部分,我试图直接执行具有transform关键字的hql文件以使用python udf。

我在CLI中测试了hql脚本" hive -f filename.hql"它工作正常。 我在spark-sql中尝试过相同的脚本,但是找不到hdfs path not error错误。我尝试以不同的方式提供hdfs路径,如下所示,但都没有工作

"/test/scripts/test.hql"

"hdfs://test.net:8020/test/scripts/test.hql"

"hdfs:///test.net:8020/test/scripts/test.hql"

还尝试在hive转换代码中给出完整路径,如下所示

USING "scl enable python27 'python hdfs://test.net:8020/user/test/scripts/TestPython.py'" 

Hive代码

add file hdfs://test.net:8020/user/test/scripts/TestPython.py;


select * from 
    (select transform (*)
    USING "scl enable python27 'python TestPython.py'" 
    as (Col_1     STRING,
    col_2        STRING,
    ...
    ..
    col_125 STRING
    )
    FROM
    test.transform_inner_temp1 a) b;

TestPython代码:

#!/usr/bin/env python
'''
Created on June 2, 2017

@author: test
'''
import sys
from datetime import datetime
import decimal
import string
D = decimal.Decimal
for line in sys.stdin:
    line = sys.stdin.readline()   
    TempList = line.strip().split('\t')
    col_1 = TempList[0]
    ... 
    ....
    col_125 = TempList[34] + TempList[32]
    outList.extend((col_1,....col_125))
    outValue = "\t".join(map(str,outList))
    print "%s"%(outValue)

所以我尝试了另一种方法,直接在spark-submit

中执行
spark-submit --master yarn-cluster  hdfs://test.net:8020/user/test/scripts/testspark.py

testspark.py

from pyspark.sql.types import StringType
from pyspark import SparkConf, SparkContext
from pyspark import SQLContext
conf = SparkConf().setAppName("gveeran pyspark test")
sc = SparkContext(conf=conf)
sqlContext = SQLContext(sc)
with open("hdfs://test.net:8020/user/test/scripts/test.hql") as fr:
   query = fr.read()
results = sqlContext.sql(query)
results.show()

但同样的问题如下

Traceback (most recent call last):
  File "PySparkTest2.py", line 7, in <module>
    with open("hdfs://test.net:8020/user/test/scripts/test.hql") as fr:
IOError: [Errno 2] No such file or directory: 'hdfs://test.net:8020/user/test/scripts/test.hql'

1 个答案:

答案 0 :(得分:0)

您可以将文件作为查询读取,然后作为spark sql作业执行

示例:-

from pyspark.sql import SparkSession
from pyspark.sql import SQLContext
sc =SparkContext.getOrCreate()
sqlCtx = SQLContext(sc)
with open("/home/hadoop/test/abc.hql") as fr:
    query = fr.read()
    print(query)
    results = sqlCtx.sql(query)