首頁  >  文章  >  後端開發  >  Python中HBase的操作範例程式碼分析

Python中HBase的操作範例程式碼分析

黄舟
黄舟原創
2017-05-07 11:02:511656瀏覽


安裝HBase

HBase是建構在HDFS上的分散式列儲存系統,主要用於大量結構化資料儲存。這裡,我們的目標只是為Python訪問HBase提供一個基本的環境,故直接下載二進位包,採用單機安裝。下載後解壓縮,修改設定檔,然後可以直接啟動HBase了。所用系統版本為ubuntu14.04。

下載

wget https://mirrors.tuna.tsinghua.edu.cn/apache/hbase/1.2.4/hbase-1.2.4-bin.tar.gz tar zxvf hbase-1.2.4-bin.tar.gz

設定

修改hbase-env.sh,設定JAVA_HOME。

export JAVA_HOME=/usr/lib/jvm/java-8-oracle

修改hbase-site.xml,設定儲存資料的根目錄。

<configuration>
    <property>
        <name>hbase.rootdir</name>
        <value>file:///home/mi/work/hbase/data</value>
    </property></configuration>

啟動

bin/start-hbase.sh  # 启动bin/hbase shell  # 进入hbase交互shell

安裝Thrift

安裝好HBase之後,還需安裝Thrift,因為其他語言呼叫HBase時,需要透過Thrift進行連線。

安裝Thrift依賴

sudo apt-get install automake bison flex g++ git libboost1.55 libevent-dev libssl-dev libtool make pkg-config

PS: libboost1.55-all-dev,在我的ubuntu14.04上安裝有點問題,所以裝的是libboost1.55。

編譯安裝

下載原始碼,解壓縮後進行編譯安裝。 Thrift下載位址

tar zxf thrift-0.10.0.tar.gzcd thrift-0.10.0/./configure 
--with-cpp --with-boost --with-python --without-csharp --with-java 
--without-erlang --without-perl --with-php --without-php_extension --without-ruby --without-haskell  
--without-gomake  # 编译耗时较长sudo make install

啟動HBase的Thrift服務

bin/hbase-daemon.sh start thrift

檢查系統進程

~/work/hbase/hbase-1.2.4/conf$ jps3009 ThriftServer4184 HMaster5932 Jps733 Main

可以看到ThriftServer已成功啟動,然後我們就可以使用多種語言,透過Thrift來造訪HBase了。

Python操作HBase

下面以Python為例來示範如何存取HBase。

安裝依賴套件

sudo pip install thriftsudo pip install hbase-thrift

Demo程式

from thrift import Thriftfrom thrift.transport 
import TSocketfrom thrift.transport import TTransportfrom thrift.protocol 
import TBinaryProtocolfrom hbase import Hbasefrom hbase.ttypes import *

transport = TSocket.TSocket(&#39;localhost&#39;, 9090)

transport = TTransport.TBufferedTransport(transport)
protocol = TBinaryProtocol.TBinaryProtocol(transport)

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

contents = ColumnDescriptor(name=&#39;cf:&#39;, maxVersions=1)# client.deleteTable(&#39;test&#39;)client.createTable(&#39;test&#39;, [contents])print client.getTableNames()# insert datatransport.open()

row = &#39;row-key1&#39;mutations = [Mutation(column="cf:a", value="1")]
client.mutateRow(&#39;test&#39;, row, mutations)
# get one rowtableName = &#39;test&#39;rowKey = &#39;row-key1&#39;result = client.getRow(tableName, rowKey)
print resultfor r in result:    
print &#39;the row is &#39;, r.row    
print &#39;the values is &#39;, r.columns.get(&#39;cf:a&#39;).value

執行結果:

[&#39;test&#39;]
[TRowResult(columns={&#39;cf:a&#39;: TCell(timestamp=1488617173254, value=&#39;1&#39;)}, row=&#39;row-key1&#39;)]
the row is  row-key1
the values is  1

以上是Python中HBase的操作範例程式碼分析的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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