1.文档编写目的
在前面Fayson介绍了在Python2的环境下《如何使用Python Impyla客户端连接Hive和Impala》,本篇文章Fayson主要介绍在Python3的环境下使用Impyla访问非Kerberos环境下的Hive以及将获取到的结果集转换为Pandas的DataFrame。
1.前置环境准备及说明
2.Python3示例代码及运行
3.总结
1.CM5.14.3和CDH5.14.2
2.Redhat7.4
3.Python 3.6.5
4.集群未启用Kerberos
2.前置环境准备及说明
在使用Impyla访问Hive前,需要安装Python的依赖包,具体需要安装的依赖包列表如下:
six
bit_array
impyla
thrift
thrift_sasl==0.2.0
1.Python3的安装目录/opt/cloudera/anaconda3
2.升级Python的pip版本
[root@cdh02 ~]# /opt/cloudera/anaconda3/bin/pip install --upgrade pip
(可左右滑动)
3.使用Python3的pip安装上述的依赖包
/opt/cloudera/anaconda3/bin/pip install six
/opt/cloudera/anaconda3/bin/pip install bit_array
/opt/cloudera/anaconda3/bin/pip install thrift
/opt/cloudera/anaconda3/bin/pip install thrift_sasl==0.2.0
/opt/cloudera/anaconda3/bin/pip install impyla
(可左右滑动)
3.Python3访问Hive示例代码
from impala.dbapi import connect
from impala.util import as_pandas
conn = connect(host='cdh01.fayson.com',port=10000,database='default',user='hive',auth_mechanism='PLAIN')
print(conn)
cursor = conn.cursor()
cursor.execute('show databases')
results = cursor.fetchall()
print(results)
cursor.execute('select * from ods_user limit 10')
df = as_pandas(cursor)
print(df)
(可左右滑动)
4.示例运行
在服务上使用如下命令运行Python代码
[root@cdh02 python_code]# /opt/cloudera/anaconda3/bin/python impyla_hive.py
(可左右滑动)
5.总结
1.使用Impyla访问Hive,需要安装impyla及其相应的依赖包(如:six、bit_array、thrift、thrift_sasl)。
2.使用Impyla访问非Kerberos环境下的Hive是,在connect方法中需要添加auth_mechanism和user两个参数,否则会报“No protocol version header”异常。
3.在安装依赖包访问Hive时遇到错误“AttributeError: 'TSocket' object has no attribute'isOpen'”,由于thrift_sasl版本问题,将thrif_salsl版本改为0.2.0即可,详细异常如下:
[root@cdh02 python_code]# /opt/cloudera/anaconda3/bin/python impaly_hive.py
Traceback (most recent call last):
File "impaly_hive.py", line 2, in <module>
conn = connect(host='cdh01.fayson.com',port=10000,database='default',user='hive',auth_mechanism='PLAIN')
File "/opt/cloudera/anaconda3/lib/python3.6/site-packages/impala/dbapi.py", line 147, in connect
auth_mechanism=auth_mechanism)
File "/opt/cloudera/anaconda3/lib/python3.6/site-packages/impala/hiveserver2.py", line 758, in connect
transport.open()
File "/opt/cloudera/anaconda3/lib/python3.6/site-packages/thrift_sasl/__init__.py", line 67, in open
if not self._trans.isOpen():
AttributeError: 'TSocket' object has no attribute 'isOpen'
(可左右滑动)
提示:代码块部分可以左右滑动查看噢
为天地立心,为生民立命,为往圣继绝学,为万世开太平。 温馨提示:要看高清无码套图,请使用手机打开并单击图片放大查看。