使用python客户端访问impala

因需要将impala仅仅作为数据源使用,而python有较好的数据分析函数,所以需要使用python客户端来获取impala中的表数据,这里的测试环境是:
操作系统:win7 (linux下也可行)
python 2.7
大数据环境:centos6.6
CDH版本:CDH5.4.1
impala 2.1.2 port:21050

1、安装Python package

pip install impyla

2、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)
<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). Get it from http://aka.ms/vcpython27
只要按照提示说的的去下载一个VC就可以了。这样就安装好了pandas。

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值