Python操作Hive准备

来源:互联网 发布:淘宝卖家如何分销 编辑:程序博客网 时间:2024/06/03 18:18

教程中使用的是Java操作hive,而我的需求是使用python操作hive,所以需要进行简单的环境配置。
使用python操作hive有两种方式:
Thrift api方式和python hive相关的包
1、Thrift api方式
根据介绍,只需要把hive/lib/py包下的文件全部拷贝到python的扩展库文件夹下即可site-packages。
拷贝完成后,启动hiveserver2服务器,使用测试代码测试:

import sysfrom hive_service import ThriftHivefrom hive_service.ttypes import HiveServerExceptionfrom thrift import Thriftfrom thrift.transport import TSocketfrom thrift.transport import TTransportfrom thrift.protocol import TBinaryProtocoldef hiveExe(sql):    try:        transport = TSocket.TSocket('192.168.83.135', 10000)        transport = TTransport.TBufferedTransport(transport)        protocol = TBinaryProtocol.TBinaryProtocol(transport)        client = ThriftHive.Client(protocol)        transport.open()        client.execute(sql)        print "The return value is : "        print client.fetchAll()        print "............"        transport.close()    except Thrift.TException, tx:        print '%s' % (tx.message)if __name__ == '__main__':    hiveExe("show databases adad;")

进行调试运行,发现走到client.execute(sql)这句时无法继续执行,目前还没找到解决办法。
2、使用pyhs2包操作hive(官方已经不再持续支持,但还可以用)
安装pyhs2依赖包:

yum install cyrus-sasl-plainyum install cyrus-sasl-develyum install python-devel.x86_64yum install cyrus-sasl-devel.x86_64

使用pip安装pyhs2
pip installpyhs2
测试代码如下:

import pyhs2conn = pyhs2.connect(host='localhost',                   port=11111,                   authMechanism="PLAIN",                   user='root',                   password='test',                   database='default')cur = conn.cursor()print cur.getDatabases()

代码执行结果如下图:
这里写图片描述
3、使用pyHive包操作hive,需要安装pyhive包,测试代码如下:

from pyhive import hivefrom TCLIService.ttypes import TOperationState# 打开hive连接hiveConn = hive.connect(host='192.168.83.135',port=11111)cursor = hiveConn.cursor()# 执行sql语句cursor.execute('show databases', async=True)# 得到执行语句的状态status = cursor.poll().operationStateprint "status:",status# 如果执行出错,循环执行,直到执行正确,可不要while status in (TOperationState.INITIALIZED_STATE, TOperationState.RUNNING_STATE):    logs = cursor.fetch_logs()    for message in logs:        print message    # If needed, an asynchronous query can be cancelled at any time with:    # cursor.cancel()    status = cursor.poll().operationState# 打印结果print cursor.fetchall()# 关闭hive连接cursor.close()hiveConn.close()

程序运行结果:
这里写图片描述
在之后的学习中,将使用pyhive进行操作。

原创粉丝点击