您的位置:首页 > 编程语言 > Python开发

使用python客户端访问impala的操作方式

2020-03-29 07:11 405 查看

因需要将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。

以上这篇使用python客户端访问impala的操作方式就是小编分享给大家的全部内容了,希望能给大家一个参考

您可能感兴趣的文章:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python impala