温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

python怎样通过thrift方式连接hive

发布时间:2021-12-02 17:34:39 来源:亿速云 阅读:214 作者:柒染 栏目:互联网科技

本篇文章给大家分享的是有关python怎样通过thrift方式连接hive,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。

hive安装完成后,如果只是本地使用,启用

nohup hive --service metastore &

[hadoop@master1 usr]$ hive

Logging initialized using configuration in file:/data/usr/hive/conf/hive-log4j.properties
hive> use fmcm;
OK
Time taken: 0.874 seconds

如果是要脚本调用,则需要启用HiveServer2,确保10000端口已经被监听(可在hive-site.xml中修改端口)

 nohup hive --service hiveserver2 &

[hadoop@master1 usr]$ netstat -an|grep 10000            
tcp        0      0 0.0.0.0:10000           0.0.0.0:*               LISTEN

HiveServer2为客户端在远程执行hive查询提供了接口,通过Thrift RPC来实现,还提供了多用户并发和认证功能。目前python可以通过pyhs2这个模块来连接HiveServer2,实现查询和取回结果的操作。

不过pyhs2已经不在维护,追新的可以参考另外2个很好的python package(已经被证明pyhs2存在性能瓶颈,最好尽快切换到pyhive)

https://github.com/dropbox/PyHive

https://github.com/cloudera/impyla

安装sasl失败的话,先安装:
yum install gcc-c++ python-devel.x86_64 cyrus-sasl-devel.x86_64

pyhs2的项目托管在github之上,地址为https://github.com/BradRuderman/pyhs2或在https://pypi.python.org/pypi/pyhs2/0.2直接下载

如果安装不成功,可以尝试先安装以下的组件:

yum install cyrus-sasl-plain
yum install cyrus-sasl-devel

安装时如果遇到报错: 

error: sasl/sasl.h: No such file or directory

可以尝试先安装sasl , ubantu可以用sudo apt-get install libsasl2-dev, CentOS可以使用anaconda的pip安装, 或者按照以下步骤安装:

curl -O -L ftp://ftp.cyrusimap.org/cyrus-sasl/cyrus-sasl-2.1.26.tar.gz
tar xzf cyrus-sasl-2.1.2.26.tar.gz
cd cyrus-sasl-2.1.26.tar.gz
./configure && make install


最后附上测试代码:
# -*- coding:utf-8 -*-
'''
采用Hive和thrift方式连接数据库
'''
import pyhs2
import sys
reload(sys)
sys.setdefaultencoding('utf8')

class HiveClient:
    def __init__(self, db_host, user, password, database, port=10000, authMechanism="PLAIN"):
      
        self.conn = pyhs2.connect(host=db_host,
                                  port=port,
                                  authMechanism=authMechanism,
                                  user=user,
                                  password=password,
                                  database=database,
                                  )

    def query(self, sql):
        with self.conn.cursor() as cursor:
            cursor.execute(sql)
            return cursor.fetch()

    def close(self):
        self.conn.close()


def main():
    """
    main process
    @rtype:
    @return:
    @note:

    """
    hive_client = HiveClient(db_host='10.24.33.3', port=10000, user='hadoop', password='hadoop',
                             database='fmcm', authMechanism='PLAIN')
    result = hive_client.query('select * from fm_news_newsaction limit 10')
    print result
    hive_client.close()


if __name__ == '__main__':
    main()

以上就是python怎样通过thrift方式连接hive,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI