python连接hive

来源:互联网 发布:js 限制ip 编辑:程序博客网 时间:2024/04/20 05:58

(1)hive 三种启动方式及用途,本文主要关注通过hiveserver(可jdbc连接)的方式启动

 1, hive  命令行模式,直接输入/hive/bin/hive的执行程序,或者输入 hive --service cli

       用于linux平台命令行查询,查询语句基本跟mysql查询语句类似

 2, hive  web界面的启动方式,hive --service hwi  

      用于通过浏览器来访问hive,提供基本的基于web的hive查询服务,可以看作是hive数据平台的demo,

具体用法可见:http://www.cnblogs.com/gpcuster/archive/2010/02/25/1673480.html   使用HIVE的WEB界面:HWI

3, hive  远程服务 (端口号10000) 启动方式,nohup hive --service hiveserver  &

      用java等程序实现通过jdbc等驱动的方式访问hive就用这种起动方式了,这个是程序员最需要的方式了。

开源工具phphiveadmin就采用的这种方式,这种方式其实启动了一个 Hive Thrift Server ,允许你使用任意语言

与hive server通信,所以如果你不会java,语言将不会成为问题。

(2)给出一个基于hiveserver的demo,这个demo可以扩展成一个基于web操作hive的离线分析工具,类似phphiveadmin。


1 准备连接hive的python代码

在使用Python连接hive之前需要将hive中的文件拷贝到python的sys.path中
cp -r $HIVE_PATH/lib/py     /usr/local/lib/python2.7/site-packages
或者将hive中连接代码,设法加入到python的eclipse项目中
总之,目的只有一个,就是用hive自己提供的python客户端代码,来连接hive
关于具体如果将第三方的python代码加入环境变量,可以参照python中添加环境变量


2 启动hive 的thrift

如果hive机器没有thrift请先安装,
确保以下服务开启:
hive --service hiveserver  


3 写代码连接hive

hive的ip是机器的ip,端口默认为10000
-------------------------------------------------------------------
import sys  
from hive_service import ThriftHive  
from hive_service.ttypes import HiveServerException  
from thrift import Thrift  
from thrift.transport import TSocket  
from thrift.transport import TTransport  
from thrift.protocol import TBinaryProtocol  
  
def hiveExe(sql):  
  
    try:  
        transport = TSocket.TSocket('127.0.0.1', 10000)   
        transport = TTransport.TBufferedTransport(transport)  
        protocol = TBinaryProtocol.TBinaryProtocol(transport)  
        client = ThriftHive.Client(protocol)  
        transport.open()  

        client.execute(sql)  

        print "The return value is : "   
        print client.fetchAll()  
        print "............"  
        transport.close()  
    except Thrift.TException, tx:  
        print '%s' % (tx.message)  
  
if __name__ == '__main__':  
    hiveExe("show tables")  
--------------------------------
0 0
原创粉丝点击