做互联网应用开发过程中,时常需要面对海量的数据存储及计算,传统的服务器已经很难再满足一些运算需求,基于hadoop/spark的大数据处理平台得到广泛的应用。本文提供一个导入数据到hive,用python读取hive数据库的例子。这实际是个比较简单的操作,但是还是存在很多坑。
1.首先第一步
需要将Mysql或者其他数据库的文件导出成CSV文件格式。当然如果你做爬虫,可以直接存到hive里面。这一步可以用图形化工具完成。
2.将csv文件导入到hive中。注意csv文件的不需要列名。
操作如下:
a. 命令行下进入hive交互式环境
b.进入你需要存储的数据库中,建立一个空表(例表:test):*注意所建表的列数需要与原csv文件对齐。
create table test(
a string,
b string,
c string
)
row format serde
'org.apache.hadoop.hive.serde2.OpenCSVSerde'
with
SERDEPROPERTIES
("separatorChar"=",","quotechar"="\"")
STORED AS TEXTFILE;
c.将csv文件导入到hive数据库中
local为本地数据,如果存储在hdfs中,可以提供hdfs的url
load data local inpath '/home/XXXX/DATA.csv' into table test;
参考网站:https://blog.csdn.net/qq_29863961/article/details/80291509
3. 使用python链接Hive
1.介绍使用pyhive模块来实现python对hive的链接读取。安装pyhive会遇到很多坑,请按一下步骤来安装:
sudo apt-get install sasl2-bin
sudo apt-get install libsasl2-dev
pip install sasl
pip install thrift
pip install thrift-sasl
pip install PyHive
pip install pyhive
2.需要介绍下的是:
pip install sasl
这个库参考资料:
https://serverfault.com/questions/644998/cyrus-sasl-2-1-26-on-ubuntu-12-04
http://askubuntu.com/questions/131580/how-do-i-install-cyrus-sasl-on-10-04-server
安装这个库,会遇到很多报错。按照第一小节中的顺序可以直接安装。
3.使用pyhive链接hive
from pyhive import hive
import pandas as pd
def LinkHive(sql_select):
connection = hive.Connection(host='localhost')
cur = connection.cursor()
cur.execute(sql_select)
columns = [col[0] for col in cursor.description]
result = [dict(zip(columns, row)) for row in cursor.fetchall()]
Main = pd.DataFrame(result)
Main.columns = title1
return Main
sql = "select * from 数据库.表名"
df = LinkHive(sql)
4.运行方法
a.需要启动hadoop所有服务。在ubuntu下敲下面命令。
1. cd /usr/local/hadoop/sbin hadoop的安装路径
2. ./start-all.sh password是hadoop配置的密码
3. hiveserver2 启动hive连接服务,启动后不要关闭终端
b.在文件根目录下 打开终端 使用 python3 XXXXX.py 启动程序。