首頁  >  文章  >  後端開發  >  詳解python操作hbase資料的方法介紹

詳解python操作hbase資料的方法介紹

高洛峰
高洛峰原創
2017-03-24 17:29:592754瀏覽

設定thrift
python使用的套件thrift
個人使用的python 編譯器是pycharm community edition. 在工程中設定中,找到project interpreter, 在在對應的工程下,找到package,然後選擇“+” 添加, 搜尋hbase-thrift (Python client for HBase Thrift interface), 然後安裝套件。
安裝伺服器端thrift。
參考官網,同時也可以在本機上安裝以終端使用。
thrift Getting Started
也可以參考安裝方法python 呼叫HBase 範例
首先,安裝thrift
下載thrift,這裡,我用的是thrift -0.7.0-dev.tar.gz 這個版本
tar xzf thrift-0.7.0-dev.tar.gz
cd thrift-0.7.0-dev
sudo ./configure –with-cpp =no –with-ruby=no
sudo make
sudo make install
然後,到HBase的源碼包裡,找到
src/main/resources/org/apache/hadoop/hbase/thrift /
執行
thrift –gen py Hbase.thrift
mv gen-py/hbase/ /usr/lib/python2.4/site-packages/ (根據python版本可能有不同)
取得資料範例1

# coding:utf-8
from thrift import Thrift
from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol
from hbase import Hbase
# from hbase.ttypes import ColumnDescriptor, Mutation, BatchMutation
from hbase.ttypes import *
import csv
def client_conn():
 # Make socket
 transport = TSocket.TSocket('hostname,like:localhost', port)
 # Buffering is critical. Raw sockets are very slow
 transport = TTransport.TBufferedTransport(transport)
 # Wrap in a protocol
 protocol = TBinaryProtocol.TBinaryProtocol(transport)
 # Create a client to use the protocol encoder
 client = Hbase.Client(protocol)
 # Connect!
 transport.open()
 return client
if __name__ == "__main__":
 client = client_conn()
 # r = client.getRowWithColumns('table name', 'row name', ['column name'])
 # print(r[0].columns.get('column name')), type((r[0].columns.get('column name')))
 result = client.getRow("table name","row name")
 data_simple =[]
 # print result[0].columns.items()
 for k, v in result[0].columns.items(): #.keys()
  #data.append((k,v))
  # print type(k),type(v),v.value,,v.timestamp
  data_simple.append((v.timestamp, v.value))
 writer.writerows(data)
 csvfile.close()
 csvfile_simple = open("data_xy_simple.csv", "wb")
 writer_simple = csv.writer(csvfile_simple)
 writer_simple.writerow(["timestamp", "value"])
 writer_simple.writerows(data_simple)
 csvfile_simple.close()
 print "finished"

會基礎的python應該知道result是個list,result[0].columns.items()是一個dict 的鍵值對。可以查詢相關資料。或透過輸出變量,觀察變數的值與類型。
說明:上面程式中transport.open()進行鏈接,在執行完後,還需要斷開transport.close()
目前只涉及到讀數據,之後還會繼續更新其他dbase操作。

以上是詳解python操作hbase資料的方法介紹的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn