教程中使用的是Java操作hive,而我的需求是使用python操作hive,所以需要进行简单的环境配置。
使用python操作hive有两种方式:
Thrift api方式和python hive相关的包
1、Thrift api方式
根据介绍,只需要把hive/lib/py包下的文件全部拷贝到python的扩展库文件夹下即可site-packages。
拷贝完成后,启动hiveserver2服务器,使用测试代码测试:
import sys
from hive_service import ThriftHive
from hive_service.ttypes import HiveServerException
from thrift import Thrift
from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol
def 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-plain
yum install cyrus-sasl-devel
yum install python-devel.x86_64
yum install cyrus-sasl-devel.x86_64
使用pip安装pyhs2
pip installpyhs2
测试代码如下:
import pyhs2
conn = 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 hive
from 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().operationState
print "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进行操作。