Python连接Impala环境准备与安装
由于计划将Impala仅用作数据源,并利用Python在数据分析方面的优势,因此需要通过Python客户端从Impala中提取表数据。本次测试的环境配置如下:
操作系统:Win7(Linux系统同样适用)
Python版本:2.7
大数据集群环境:CentOS 6.6
CDH版本:CDH5.4.1
Impala版本:2.1.2,端口:21050
第一步:安装Python相关包
执行命令:pip install impyla
第二步:Python客户端与Impala交互
2.1 连接Impala服务
>>> 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()将返回一个空列表。
>>> 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)
>>> df
id name value
0 1 tom f
1 2 jerry t
>>>
注:前提是Python环境中已安装Pandas。可通过pip install pandas在线安装。安装过程中可能会提示需要Microsoft Visual C++ 9.0(Unable to find vcvarsall.bat),此时可前往http://aka.ms/vcpython27下载所需组件。
只需按照提示下载并安装VC编译器即可顺利完成Pandas的安装。
以上即为使用Python客户端访问Impala的完整操作指南,希望能为大家提供参考,欢迎支持本站。