HBAse Java API使用操作例
HBAse APIの使用により、以下の例では、HBAseに対する一般的な操作を例示する.
がんばって!
package net.csdn.jtlyuan;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.KeyValue;
import org.apache.hadoop.hbase.client.HBaseAdmin;
import org.apache.hadoop.hbase.client.HTable;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.ResultScanner;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.io.BatchUpdate;
public class HBaseDBDao {
// HBaseConfiguration
static HBaseConfiguration cfg =null;
static {
Configuration configuration = new Configuration();
cfg = new HBaseConfiguration(configuration);
}
// , ,
public static void createTable(String tableName,String columnFarily)throws Exception{
HBaseAdmin admin = new HBaseAdmin(cfg);
if(admin.tableExists(tableName)){
System.out.println(tableName+" !");
System.exit(0);
}else{
HTableDescriptor tableDesc = new HTableDescriptor(tableName);
tableDesc.addFamily(new HColumnDescriptor(columnFarily+":"));
System.out.println(" !");
}
}
// , HTable。 BatchUpdate data
public static void addData(String tableName,String row,String columnFamily,String column,String data)throws Exception{
HTable table = new HTable(cfg,tableName);
BatchUpdate update = new BatchUpdate(row);
update.put(columnFamily+":"+column, data.getBytes());
table.commit(update);
System.out.println(" !");
}
// , HTable Scan
public static void getAllData(String tableName)throws Exception{
HTable table = new HTable(cfg,tableName);
Scan scan = new Scan();
ResultScanner rs = table.getScanner(scan);
for(Result r:rs){
for(KeyValue kv:r.raw()){
System.out.println(new String(kv.getColumn())+new String(kv.getValue()));
}
}
}
//
public static void main(String[] args){
try{
String tableName = "student";
HBaseDBDao.createTable(tableName, "c1");
HBaseDBDao.addData(tableName, "row1", "c1", "1", "this is row 1 column c1:c1");
HBaseDBDao.getAllData(tableName);
}catch(Exception e){
e.printStackTrace();
}
}
}
がんばって!