1. 程式人生 > >將資料匯入Hive資料庫中,使用python連結Hive讀取資料庫,轉化成pandas的dataframe

將資料匯入Hive資料庫中,使用python連結Hive讀取資料庫,轉化成pandas的dataframe

   做網際網路應用開發過程中,時常需要面對海量的資料儲存及計算,傳統的伺服器已經很難再滿足一些運算需求,基於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;

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 = columns 
    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 啟動程式。