实例讲解hadoop中的hive查询(python语言实现)

条件,假设配置好了hadoop和hive,并可以正常运行

首先,要外部查询hive,你需要安装thrift和fb303,或许有别的办法,但我实际应用过程中看来,这是最简单的途径。hive本身提供了thrift的接口。文件在hive解压缩后如下路径中

hive/hive-0.7.1/src/service/if/hive_service.thrift

然后复制四个文件
metastore/if/hive_metastore.thrift
src/service/if/hive_service.thrift
ql/if/queryplan.thrift
thrift源码下fb303中的fb303.thrift。

编辑hive_service.thrift,将其中include其他三个文件的路径修改为正确的路径。保存退出,运行thrift

#thrift -r --gen python hive_service.thrift

将生成的python放入/usr/lib/python/site-packages下,然后编写如下脚本

#!/usr/bin/python
#-*-coding:UTF-8 -*-
import sys
import os
import string
import re
import MySQLdb

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(hsql,dbname):
#定义hive查询函数
                try:
                                transport = TSocket.TSocket('192.168.10.1', 10000)
                                transport = TTransport.TBufferedTransport(transport)
                                protocol = TBinaryProtocol.TBinaryProtocol(transport)

                                client = ThriftHive.Client(protocol)
                                transport.open()

                                client.execute('ADD jar /opt/modules/hive/hive-0.7.1/lib/hive-contrib-0.7.1.jar')

                                client.execute("use "+dbname)
                                row = client.fetchOne()
                                #使用库名,只需一次fetch,用fetchOne

                                client.execute(hsql)
                                return client.fetchAll()
                                #查询所有数据,用fetchAll()

                                transport.close()

                except Thrift.TException, tx:
                                print '%s' % (tx.message)

def mysqlExe(sql):
                try:
                                conn = MySQLdb.connect(user="test",passwd="test123",host="127.0.0.1",db="active2_ip",port=5029)
                except Exception,data:
                                print "Could not connect to MySQL server.:",data
                try:
                                cursor = conn.cursor()
                                cursor.execute(sql)
                                return row
                                cursor.commit()
                                cursor.close()
                                conn.close()
                except Exception,data:
                                print "Could not Fetch anything:",data

dbname = "active2"
date = os.popen("date -d '1 day ago' +%Y%m%d").read().strip()
#shell方式取昨天日期,读取并去前后\n
date.close()

sql = "create table IF NOT EXISTS "+dbname+"_group_ip_"+date+" like "+dbname+"_group_ip;load data infile '/tmp/"+dbname+"_"+date+".csv' into table "+dbname+"_group_ip_"+date+" FIELDS TERMINATED BY ','"
#以模板表创建日期表,并load data到该表中

hsql = "insert overwrite local directory '/tmp/"+dbname+"_"+date+"' select count(version) as vc,stat_hour,type,version,province,city,isp from "+dbname+"_"+date+" group by province,city,version,type,stat_hour,isp"
#hive查询,并将查询结果导出到本地/tmp/active2_20111129目录下,可能生成多个文件

hiveExe(hsql, dbname)
#执行查询

os.system("sudo cat /tmp/"+dbname+"_"+date+"/* > /tmp/tmplog ")
#将多个文件通过shell合并为一个文件tmplog

file1 = open("/tmp/tmplog", 'r')
#打开合并后的临时文件
file2 = open("/tmp/"+dbname+"_"+date+".csv",'w')
#打开另一个文件,做文字替换。因为hive导出结果,其分隔符为特殊字符。所以需要做替换,格式为csv,故用逗号分隔
sep = ','
for line in file1:
                tmp = line[:-1].split('\x01')
                #hive导出文件分隔符为ascii中的001,\x01是16进制,但其实也就是十进制的1
                replace = sep.join(tmp)
                file2.write(replace+"\n")


file1.close()
file2.close()

os.system("sudo rm -f /tmp/tmplog")
#删除临时的tmplog

mysqlExe(sql)
#执行mysql查询,创建表和加载数据。
os.system("sudo rm -f /tmp/"+dbname+"_"+date)

其实难点主要是如何通过thrift来查询hive。还有就是hive在dump数据时,如果写insert overwrite directory,会dump到hdfs里,必须写insert overwrite local directory,才会dump到当前工作机。

再一个就是注意导出文件内容中的分隔符,其他都跟正常数据库操作是一样的。

PS:我是个python新手,刚用时间不长,所以用了很多命令行去获取当前状态值,这个熟悉python的人可以改一下。
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
基于hadoopHive数据仓库JavaAPI简单调用的实例,关于Hive的简介在此不赘述。hive提供了三种用户接口:CLI,JDBC/ODBC和 WebUI CLI,即Shell命令行 JDBC/ODBC 是 Hive 的Java,与使用传统数据库JDBC的方式类似 WebGUI是通过浏览器访问 Hive 本文主要介绍的就是第二种用户接口,直接进入正题。 1、Hive 安装: 1)hive的安装请参考网上的相关文章,测试时只在hadoop一个节点上安装hive即可。 2)测试数据data文件'\t'分隔: 1 zhangsan 2 lisi 3 wangwu 3)将测试数据data上传到linux目录下,我放置在:/home/hadoop01/data 2、在使用 JDBC 开发 Hive 程序时, 必须首先开启 Hive 的远程服务接口。使用下面命令进行开启: Java代码 收藏代码 hive --service hiveserver >/dev/null 2>/dev/null & 我们可以通过CLI、Client、Web UI等Hive提供的用户接口来和Hive通信,但这三种方式最常用的是CLI;Client 是Hive的客户端,用户连接至 Hive Server。在启动 Client 模式的时候,需要指出Hive Server所在节点,并且在该节点启动 Hive Server。 WUI 是通过浏览器访问 Hive。今天我们来谈谈怎么通过HiveServer来操作Hive。   Hive提供了jdbc驱动,使得我们可以用Java代码来连接Hive并进行一些类关系型数据库的sql语句查询等操作。同关系型数据库一样,我们也需要将Hive的服务打开;在Hive 0.11.0版本之前,只有HiveServer服务可用,你得在程序操作Hive之前,必须在Hive安装的服务器上打开HiveServer服务,如下: 1 [wyp@localhost/home/q/hive-0.11.0]$ bin/hive --service hiveserver -p10002 2 Starting Hive Thrift Server 上面代表你已经成功的在端口为10002(默认的端口是10000)启动了hiveserver服务。这时候,你就可以通过Java代码来连接hiveserver,代码如下:
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值