首先要先引用Thrift
<?
//include thrift路徑
$GLOBALS['THRIFT_ROOT'] = '/var/www/hbase/thrift';
require_once( $GLOBALS['THRIFT_ROOT'].'/Thrift.php' );
require_once( $GLOBALS['THRIFT_ROOT'].'/transport/TSocket.php' );
require_once( $GLOBALS['THRIFT_ROOT'].'/transport/TBufferedTransport.php' );
require_once( $GLOBALS['THRIFT_ROOT'].'/protocol/TBinaryProtocol.php' );
require_once( $GLOBALS['THRIFT_ROOT'].'/packages/Hbase/Hbase.php' );
//建立連線
$socket = new TSocket( 'johnson-cloud', 9090 );
$socket->setSendTimeout( 10000 ); // Ten seconds
$socket->setRecvTimeout( 20000 ); // Twenty seconds
$transport = new TBufferedTransport( $socket );
$protocol = new TBinaryProtocol( $transport );
$client = new HbaseClient( $protocol );
//啟動
$transport->open();
/*程式碼寫在這*/
$transport->close();
?>
1.列出hbase 裡的所有 table
<?php
echo( "listing tables...\n" );
$tables = $client->getTableNames();
sort( $tables );
foreach ( $tables as $name )
{
echo $name."\n";
}
?>
2.刪除table
<?php
$name = "test2"; //要刪除的資料表
if($client->isTableEnabled($name))
{
echo "關閉".$name."資料表\n";
$client->disableTable($name);
}
echo "刪除中...\n";
$client->deleteTable($name);
echo "刪除完成";
?>
3.新增table
<?php
//定義columns 的物件結構,一個Column需要new出一個ColumnDescriptor物件
$columns = array(
new ColumnDescriptor( array(
'name' => 'name:'
) ),
new ColumnDescriptor( array(
'name'=> 'scores:',
) )
);
$t = "test2";//Table name
echo( "creating table: {$t}\n" );
try
{
$client->createTable( $t, $columns );
}
catch ( AlreadyExists $ae )
{
echo( "WARN: {$ae->message}\n" );
}
?>
4.列出table內的column family
<?php
//列出 table內的column family
$t = "results";//資料表名稱
echo( "column families in {$t}:\n" );
$descriptors = $client->getColumnDescriptors( $t );
asort( $descriptors );
foreach ( $descriptors as $col )
{
echo( " column: {$col->name}, maxVer: {$col->maxVersions}\n" );
}
?>
5.寫入資料
<?php
$t = "results";//Table name
$row = "s96113106";//row name
$valid = "Tom";
$mutations = array(
new Mutation( array(
'column' => 'name:',
'value' => $valid
) )
);
$client->mutateRow( $t, $row, $mutations );
echo "新增成功";
?>
6.讀取資料,取得一個 column value
<?php
include "ThriftLib.php";
$table_name = 'results';//Table name
$row_name = 's96113106';//row name
$fam_col_name = 'scores:math';//column name
$arr = $client->get($table_name, $row_name , $fam_col_name);
foreach ( $arr as $k=>$v )
{
//// $k = TCell物件
echo "value = {$v->value} , <br> ";
echo "timestamp = {$v->timestamp} <br>";
}
?>