Python通过impyla连接Impala进行数据查询与处理
本文介绍如何使用Python客户端通过impyla库连接Impala数据库。内容涵盖环境配置、HS2服务端口设置、SQL执行、结果遍历及利用Pandas进行数据分析的方法。针对大数据集,建议通过CTAS写入HDFS,并解决了pandas安装中常见的Visual C++依赖问题。
环境配置与前置准备
由于仅需将Impala作为数据源,且Python具备强大的数据分析函数库,因此需要通过Python客户端获取Impala中的表数据。本次测试环境配置如下:
操作系统:Windows 7(Linux环境下同样适用)
Python版本:2.7
大数据集群环境:CentOS 6.6
CDH版本:CDH 5.4.1
Impala版本:2.1.2,默认端口:21050
安装impyla库
第一步:安装Python相关包
执行命令:pip install impyla
第二步:Python客户端与Impala进行交互
2.1 建立Impala连接
连接Impala与执行SQL查询
>>> from impala.dbapi import connect
>>> conn = connect(host='my.impala.host', port=21050)
>>> cur = conn.cursor()
注意:务必确保连接的是HS2服务端口,而非Beeswax服务。在Cloudera集群管理中,HS2的默认端口为21050(Beeswax默认端口为21000)。
2.2 对Impala执行SQL查询
>>> cur.execute('SHOW TABLES')
>>> cur.fetchall()
[('defect_code_dim',), ('gxzl_ca_materialinfo',), ('gxzl_cg_materialinfo',), ('gxzl_defect2',), ('gxzl_defects',), ('gxzl_defects_hd',), ('gxzl_fx_class',), ('gxzl_fx_leftmidright',), ('gxzl_fx_topandbot',), ('gxzl_jiejing_2cc_slab',), ('gxzl_kgx_drw',), ('gxzl_kgx_drw_tmp',), ('gxzl_rz_materialinfo',), ('gxzl_sdbase_defects',), ('gxzl_test',), ('new_table',), ('ouye_transactionlog',), ('ouye_userinfo',), ('simple_test',), ('t0',), ('t_100m_hdfs',), ('t_100m_test',), ('t_10m_hdfs',), ('target1',), ('target2',), ('target3',), ('test',), ('tianchi_mobile_recommend_train_full',), ('tianchi_mobile_recommend_train_item',), ('tianchi_mobile_recommend_train_user',), ('tianchi_mobile_recommend_train_useritem',)]
>>> cur.execute('SELECT * FROM test')
>>> cur.description
[('id', 'DOUBLE', None, None, None, None, None), ('name', 'STRING', None, None, None, None, None), ('value', 'STRING', None, None, None, None, None)]
>>> cur.fetchall()
[(1.0, 'tom', 'f'), (2.0, 'jerry', 't')]
>>>
注意:从服务器获取数据会清除缓存,因此第二次调用.fetchall()将返回空列表。
查询结果处理与Pandas转换
>>> cur.fetchall()
[(1.0, 'tom', 'f'), (2.0, 'jerry', 't')]
>>> cur.fetchall()
[]
>>>
2.3 遍历查询结果
>>> cur.execute('SELECT * FROM test')
>>> for row in cur:
print row[1] == 1.0
False
False
注:Python索引从0开始。上述示例仍采用缓存方式获取数据。
若数据集规模较小,可使用此方式;若需处理大量数据,建议使用CREATE TABLE AS SELECT语句将结果写入HDFS。
2.4 将查询结果转换为Python中的Pandas DataFrames
除了遍历结果外,还可以将结果转换为Pandas数据框对象,以便进行更深入的数据分析:
>>> from impala.dbapi import connect
>>> conn = connect(host='my.impala.host', port=21050)
>>> cur = conn.cursor()
>>> from impala.util import as_pandas
>>> cur.execute('SELECT * FROM test')
>>> df = as_pandas(cur)
>>> type(df)
<class 'pandas.core.frame.DataFrame'>
>>> df
id name value
0 1 tom f
1 2 jerry t
>>>
注:前提是在Python中已安装pandas。可通过pip install pandas在线安装。安装过程中若提示:Microsoft Visual C++ 9.0 is required (Unable to find vcvarsall.bat),需从http://aka.ms/vcpython27获取相关组件。
按照提示下载并安装VC组件即可解决该问题,从而完成pandas的安装。
以上即为使用Python客户端访问Impala的完整操作流程,供参考。
本站声明
本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。













