天天看點

将資料導入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;
           

參考網站: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 = 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 啟動程式。