導航:首頁 > 編程語言 > hbasejava基本操作

hbasejava基本操作

發布時間:2022-09-19 07:31:37

① 如何使用java API操作Hbase

寫了個Hbase新的api的增刪改查的工具類,以供參考,直接拷貝代碼就能用,散仙覺得基礎的功能,都有了,代碼如下:

package com.dhgate.hbase.test;

import java.util.ArrayList;
import java.util.List;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.CellUtil;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Delete;
import org.apache.hadoop.hbase.client.Get;
import org.apache.hadoop.hbase.client.HBaseAdmin;
import org.apache.hadoop.hbase.client.HTable;
import org.apache.hadoop.hbase.client.Put;
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.filter.PageFilter;
import org.apache.hadoop.hbase.filter.PrefixFilter;
import org.apache.hadoop.hbase.util.Bytes;

/**
* 基於新的API
* Hbase0.96版本
* 寫的工具類
*
* @author qindongliang
* 大數據技術交流群: 376932160
*
* **/
public class HbaseCommons {

static Configuration conf=HBaseConfiguration.create();
static String tableName="";

public static void main(String[] args)throws Exception {

//String tableName="test";
//createTable(tableName, null);

}

/**
* 批量添加數據
* @param tableName 標名字
* @param rows rowkey行健的集合
* 本方法僅作示例,其他的內容需要看自己義務改變
*
* **/
public static void insertList(String tableName,String rows[])throws Exception{
HTable table=new HTable(conf, tableName);
List<Put> list=new ArrayList<Put>();
for(String r:rows){
Put p=new Put(Bytes.toBytes(r));
//此處示例添加其他信息
//p.add(Bytes.toBytes("family"),Bytes.toBytes("column"), 1000, Bytes.toBytes("value"));
list.add(p);
}
table.put(list);//批量添加
table.close();//釋放資源
}

/**
* 創建一個表
* @param tableName 表名字
* @param columnFamilys 列簇
*
* **/
public static void createTable(String tableName,String[] columnFamilys)throws Exception{
//admin 對象
HBaseAdmin admin=new HBaseAdmin(conf);
if(admin.tableExists(tableName)){
System.out.println("此表,已存在!");
}else{
//舊的寫法
//HTableDescriptor tableDesc=new HTableDescriptor(tableName);
//新的api
HTableDescriptor tableDesc=new HTableDescriptor(TableName.valueOf(tableName));

for(String columnFamily:columnFamilys){
tableDesc.addFamily(new HColumnDescriptor(columnFamily));
}

admin.createTable(tableDesc);
System.out.println("建表成功!");

}
admin.close();//關閉釋放資源

}

/**
* 刪除一個表
* @param tableName 刪除的表名
* */
public static void deleteTable(String tableName)throws Exception{
HBaseAdmin admin=new HBaseAdmin(conf);
if(admin.tableExists(tableName)){
admin.disableTable(tableName);//禁用表
admin.deleteTable(tableName);//刪除表
System.out.println("刪除表成功!");
}else{
System.out.println("刪除的表不存在!");
}
admin.close();
}

/**
* 插入一條數據
* @param tableName 表明
* @param columnFamily 列簇
* @param column 列
* @param value 值
*
* ***/
public static void insertOneRow(String tableName,String rowkey,String columnFamily,String column,String value)throws Exception{

HTable table=new HTable(conf, tableName);
Put put=new Put(Bytes.toBytes(rowkey));
put.add(Bytes.toBytes(columnFamily), Bytes.toBytes(column), Bytes.toBytes(value));
table.put(put);//放入表
table.close();//釋放資源

}

/**
* 刪除一條數據
* @param tableName 表名
* @param row rowkey行鍵
*
* */
public static void deleteOneRow(String tableName,String row)throws Exception{

HTable table=new HTable(conf, tableName);
Delete delete=new Delete(Bytes.toBytes(row));
table.delete(delete);
table.close();
}

/**
* 刪除多條數據
* @param tableName 表名
* @param rows 行健集合
*
* **/
public static void deleteList(String tableName,String rows[])throws Exception{
HTable table=new HTable(conf, tableName);
List<Delete> list=new ArrayList<Delete>();
for(String row:rows){
Delete del=new Delete(Bytes.toBytes(row));
list.add(del);
}
table.delete(list);
table.close();//釋放資源

}

/**
* 獲取一條數據,根據rowkey
* @param tableName 表名
* @param row 行健
*
* **/
public static void getOneRow(String tableName,String row)throws Exception{
HTable table=new HTable(conf, tableName);
Get get=new Get(Bytes.toBytes(row));
Result result=table.get(get);
printRecoder(result);//列印記錄
table.close();//釋放資源
}

/**
* 查看某個表下的所有數據
*
* @param tableName 表名
* */
public static void showAll(String tableName)throws Exception{
HTable table=new HTable(conf, tableName);
Scan scan=new Scan();
ResultScanner rs=table.getScanner(scan);
for(Result r:rs){
printRecoder(r);//列印記錄
}
table.close();//釋放資源
}

/**
* 查看某個表下的所有數據
*
* @param tableName 表名
* @param rowKey 行健
* */
public static void ScanPrefixByRowKey(String tableName,String rowKey)throws Exception{
HTable table=new HTable(conf, tableName);
Scan scan=new Scan();
scan.setFilter(new PrefixFilter(Bytes.toBytes(rowKey)));
ResultScanner rs=table.getScanner(scan);
for(Result r:rs){
printRecoder(r);//列印記錄
}
table.close();//釋放資源
}

/**
* 查看某個表下的所有數據
*
* @param tableName 表名
* @param rowKey 行健掃描
* @param limit 限制返回數據量
* */
public static void ScanPrefixByRowKeyAndLimit(String tableName,String rowKey,long limit)throws Exception{
HTable table=new HTable(conf, tableName);
Scan scan=new Scan();
scan.setFilter(new PrefixFilter(Bytes.toBytes(rowKey)));
scan.setFilter(new PageFilter(limit));
ResultScanner rs=table.getScanner(scan);
for(Result r:rs){
printRecoder(r);//列印記錄
}
table.close();//釋放資源
}

/**
* 根據rowkey掃描一段范圍
* @param tableName 表名
* @param startRow 開始的行健
* @param stopRow 結束的行健
* **/
public void scanByStartAndStopRow(String tableName,String startRow,String stopRow)throws Exception{
HTable table=new HTable(conf, tableName);
Scan scan=new Scan();
scan.setStartRow(Bytes.toBytes(startRow));
scan.setStopRow(Bytes.toBytes(stopRow));
ResultScanner rs=table.getScanner(scan);
for(Result r:rs){
printRecoder(r);
}
table.close();//釋放資源

}
/**
* 掃描整個表裡面具體的某個欄位的值
* @param tableName 表名
* @param columnFalimy 列簇
* @param column 列
* **/
public static void getValueDetail(String tableName,String columnFalimy,String column)throws Exception{

HTable table=new HTable(conf, tableName);
Scan scan=new Scan();
ResultScanner rs=table.getScanner(scan);
for(Result r:rs){
System.out.println("值: " +new String(r.getValue(Bytes.toBytes(columnFalimy), Bytes.toBytes(column))));
}
table.close();//釋放資源

}

/**
* 列印一條記錄的詳情
*
* */
public static void printRecoder(Result result)throws Exception{
for(Cell cell:result.rawCells()){
System.out.print("行健: "+new String(CellUtil.cloneRow(cell)));
System.out.print("列簇: "+new String(CellUtil.cloneFamily(cell)));
System.out.print(" 列: "+new String(CellUtil.cloneQualifier(cell)));
System.out.print(" 值: "+new String(CellUtil.cloneValue(cell)));
System.out.println("時間戳: "+cell.getTimestamp());
}
}

}

② 如何使用Java API操作Hbase

HBase提供了對HBase進行一系列的管理涉及到對表的管理、數據的操作java api。 常用的API操作有: 1、 對表的創建、刪除、顯示以及修改等,可以用HBaseAdmin,一旦創建了表,那麼可以通過HTable的實例來訪問表,每次可以往表裡增加數據。

③ 如何使用Java API操作Hbase

通過對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();
}
}
}

④ 如何用eclipse中java控制linux中虛擬機中的hbase資料庫

一、新建本地java工程
file->new->java project

二、添加jar包和配置文件
1、添加JAR包
右擊Propertie在彈出的快捷菜單中選擇Java Build Path對話框,在該對話框中單擊Libraries選項卡,在該選項卡下單擊
Add External JARs按鈕,定位到$HBASE/lib目錄下,並選取如下JAR包。
hadoop-core-1.0.0.jar
commons-loggings-version.jar
commons-cli-version.jar
commons-lang-version.jar
commons-configuration-version.jar
hbase-0.94.1.jar
zookeeper-3.4.3.jar
slf4j-api-1.5.8.jar
slf4j-log4j12-1.5.8.jar
log4j-1.2.16.jar
protobuf-java-2.4.1.jar
2、添加hbase-site.xml配置文件
在工程根目錄下創建conf文件夾,將$HBASE_HOME/conf/目錄中的hbase-site.xml文件復制到該文件夾中。通過右鍵
選擇Propertie->Java Build Path->Libraries->Add Class Folder。

3、windows下開發HBase應用程序,HBase部署在linux環境中,在運行調試時可能會出現無法找到主機,類似異常信息如下:java.net.UnknownHostException: unknown host: master
解決辦法如下:在C:\WINDOWS\system32\drivers\etc\hosts文件中添加如下信息
192.168.2.34 master

⑤ 如何使用Java API操作Hbase

先在靜態代碼塊中把系統中需要用到的表都獲取一遍,獲取完之後立即關閉該表,以期增加真正的服務的代碼中,第一次實例化HTable對象的效率。

//這是我對外提供服務的類
publicclassHBaseQu
{

//SignHBase.getConfiguration()是從配置文件中獲取
//org.apache.hadoop.conf.Configuration的一個對象
//定義一個全局的HTablePool
=newHTablePool(
SignHBase.getConfiguration(),Integer.MAX_VALUE);
//初始化所用到的HTablePool,從pool中get一個需要用到的表,get完畢,立即關閉,
//以後每增加一個介面,如果需要用到一個新表的話,就在此處增加一次獲取表,然後關閉它的代碼。
static
{
HTabletable=null;
//從池裡獲取一個表,然後關閉它(類似於充血)try{
table=(HTable)hTablePool.getTable(tableName);
if(null!=table)
{
table.close();
}
}
catch(IOExceptione)
{
e.printStackTrace();
}

//獲取另外一個表
try
{
table=(HTable)hTablePool.getTable(tableName2);
if(null!=table)
{
table.close();
}
}
catch(IOExceptione)
{
e.printStackTrace();
}
}
}

在真正的服務的代碼中,直接使用pool.getTable(tableName)即可快速實例化該表。如下所示:

HTabletable=null;//定義HTable
ResultScannerrs=null;//定義接收結果的ResultScanner對象
try
{
//實例化HTable對象
table=(HTable)HBaseQu.hTablePool.getTable(tablename);
Scans=newScan();//實例化Scan對象
s.setFilter(newPrefixFilter(rowPrifix.getBytes()));//添加過濾器
s.addColumn(Bytes.toBytes(family),Bytes.toBytes(qualifier));
rs=table.getScanner(s);//獲取結果
for(Resultr:rs)
{//循環處理行
KeyValue[]kv=r.raw();
for(inti=0;i<kv.length;i++)
{
value.add(newString(kv[i].getRow(),"UTF-8")+":---:"
+newString(kv[i].getFamily())+":"
+newString(kv[i].getQualifier())+":---:"
+newString(kv[i].getValue()));
}
}
}
catch(Exceptione)
{
e.printStackTrace();
returnnull;
}
finally
{
//關閉打開的資源
if(null!=rs)
{
rs.close();
}
try
{
if(null!=table)
{
table.close();
}
}
catch(IOExceptione)
{
e.printStackTrace();
}
}

⑥ 如何使用Java API操作Hbase

寫了個Hbase新的api的增刪改查的工具類,以供參考,代碼如下:
package com.dhgate.hbase.test;

import java.util.ArrayList;
import java.util.List;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.CellUtil;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Delete;
import org.apache.hadoop.hbase.client.Get;
import org.apache.hadoop.hbase.client.HBaseAdmin;
import org.apache.hadoop.hbase.client.HTable;
import org.apache.hadoop.hbase.client.Put;
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.filter.PageFilter;
import org.apache.hadoop.hbase.filter.PrefixFilter;
import org.apache.hadoop.hbase.util.Bytes;
/**
* 基於新的API
* Hbase0.96版本
* 寫的工具類
*
* **/
public class HbaseCommons {

static Configuration conf=HBaseConfiguration.create();
static String tableName="";

public static void main(String[] args)throws Exception {

//String tableName="test";
//createTable(tableName, null);

}

/**
* 批量添加數據
* @param tableName 標名字
* @param rows rowkey行健的集合
* 本方法僅作示例,其他的內容需要看自己義務改變
*
* **/
public static void insertList(String tableName,String rows[])throws Exception{
HTable table=new HTable(conf, tableName);
List<Put> list=new ArrayList<Put>();
for(String r:rows){
Put p=new Put(Bytes.toBytes(r));
//此處示例添加其他信息
//p.add(Bytes.toBytes("family"),Bytes.toBytes("column"), 1000, Bytes.toBytes("value"));
list.add(p);
}
table.put(list);//批量添加
table.close();//釋放資源
}

/**
* 創建一個表
* @param tableName 表名字
* @param columnFamilys 列簇
*
* **/
public static void createTable(String tableName,String[] columnFamilys)throws Exception{
//admin 對象
HBaseAdmin admin=new HBaseAdmin(conf);
if(admin.tableExists(tableName)){
System.out.println("此表,已存在!");
}else{
//舊的寫法
//HTableDescriptor tableDesc=new HTableDescriptor(tableName);
//新的api
HTableDescriptor tableDesc=new HTableDescriptor(TableName.valueOf(tableName));

for(String columnFamily:columnFamilys){
tableDesc.addFamily(new HColumnDescriptor(columnFamily));
}

admin.createTable(tableDesc);
System.out.println("建表成功!");

}
admin.close();//關閉釋放資源

}

/**
* 刪除一個表
* @param tableName 刪除的表名
* */
public static void deleteTable(String tableName)throws Exception{
HBaseAdmin admin=new HBaseAdmin(conf);
if(admin.tableExists(tableName)){
admin.disableTable(tableName);//禁用表
admin.deleteTable(tableName);//刪除表
System.out.println("刪除表成功!");
}else{
System.out.println("刪除的表不存在!");
}
admin.close();
}

/**
* 插入一條數據
* @param tableName 表明
* @param columnFamily 列簇
* @param column 列
* @param value 值
*
* ***/
public static void insertOneRow(String tableName,String rowkey,String columnFamily,String column,String value)throws Exception{

HTable table=new HTable(conf, tableName);
Put put=new Put(Bytes.toBytes(rowkey));
put.add(Bytes.toBytes(columnFamily), Bytes.toBytes(column), Bytes.toBytes(value));
table.put(put);//放入表
table.close();//釋放資源

}

/**
* 刪除一條數據
* @param tableName 表名
* @param row rowkey行鍵
*
* */
public static void deleteOneRow(String tableName,String row)throws Exception{

HTable table=new HTable(conf, tableName);
Delete delete=new Delete(Bytes.toBytes(row));
table.delete(delete);
table.close();
}

/**
* 刪除多條數據
* @param tableName 表名
* @param rows 行健集合
*
* **/
public static void deleteList(String tableName,String rows[])throws Exception{
HTable table=new HTable(conf, tableName);
List<Delete> list=new ArrayList<Delete>();
for(String row:rows){
Delete del=new Delete(Bytes.toBytes(row));
list.add(del);
}
table.delete(list);
table.close();//釋放資源

}

/**
* 獲取一條數據,根據rowkey
* @param tableName 表名
* @param row 行健
*
* **/
public static void getOneRow(String tableName,String row)throws Exception{
HTable table=new HTable(conf, tableName);
Get get=new Get(Bytes.toBytes(row));
Result result=table.get(get);
printRecoder(result);//列印記錄
table.close();//釋放資源
}

/**
* 查看某個表下的所有數據
*
* @param tableName 表名
* */
public static void showAll(String tableName)throws Exception{
HTable table=new HTable(conf, tableName);
Scan scan=new Scan();
ResultScanner rs=table.getScanner(scan);
for(Result r:rs){
printRecoder(r);//列印記錄
}
table.close();//釋放資源
}

/**
* 查看某個表下的所有數據
*
* @param tableName 表名
* @param rowKey 行健
* */
public static void ScanPrefixByRowKey(String tableName,String rowKey)throws Exception{
HTable table=new HTable(conf, tableName);
Scan scan=new Scan();
scan.setFilter(new PrefixFilter(Bytes.toBytes(rowKey)));
ResultScanner rs=table.getScanner(scan);
for(Result r:rs){
printRecoder(r);//列印記錄
}
table.close();//釋放資源
}

/**
* 查看某個表下的所有數據
*
* @param tableName 表名
* @param rowKey 行健掃描
* @param limit 限制返回數據量
* */
public static void ScanPrefixByRowKeyAndLimit(String tableName,String rowKey,long limit)throws Exception{
HTable table=new HTable(conf, tableName);
Scan scan=new Scan();
scan.setFilter(new PrefixFilter(Bytes.toBytes(rowKey)));
scan.setFilter(new PageFilter(limit));
ResultScanner rs=table.getScanner(scan);
for(Result r:rs){
printRecoder(r);//列印記錄
}
table.close();//釋放資源
}

/**
* 根據rowkey掃描一段范圍
* @param tableName 表名
* @param startRow 開始的行健
* @param stopRow 結束的行健
* **/
public void scanByStartAndStopRow(String tableName,String startRow,String stopRow)throws Exception{
HTable table=new HTable(conf, tableName);
Scan scan=new Scan();
scan.setStartRow(Bytes.toBytes(startRow));
scan.setStopRow(Bytes.toBytes(stopRow));
ResultScanner rs=table.getScanner(scan);
for(Result r:rs){
printRecoder(r);
}
table.close();//釋放資源

}
/**
* 掃描整個表裡面具體的某個欄位的值
* @param tableName 表名
* @param columnFalimy 列簇
* @param column 列
* **/
public static void getValueDetail(String tableName,String columnFalimy,String column)throws Exception{

HTable table=new HTable(conf, tableName);
Scan scan=new Scan();
ResultScanner rs=table.getScanner(scan);
for(Result r:rs){
System.out.println("值: " +new String(r.getValue(Bytes.toBytes(columnFalimy), Bytes.toBytes(column))));
}
table.close();//釋放資源

}

/**
* 列印一條記錄的詳情
*
* */
public static void printRecoder(Result result)throws Exception{
for(Cell cell:result.rawCells()){
System.out.print("行健: "+new String(CellUtil.cloneRow(cell)));
System.out.print("列簇: "+new String(CellUtil.cloneFamily(cell)));
System.out.print(" 列: "+new String(CellUtil.cloneQualifier(cell)));
System.out.print(" 值: "+new String(CellUtil.cloneValue(cell)));
System.out.println("時間戳: "+cell.getTimestamp());
}
}

}

⑦ 如何使用Java API操作Hbase

C:\Program Files\Java
D:\Program Files\Java
D:\Java
安裝後可出現jre和jdk兩個目錄,其中jre為運行環境,jdk為開發環境。
配置JDK環境變數
右鍵我的電腦,選擇屬性,選擇高級選項卡,點擊環境變數進入環境變數設置頁,進行JVM環境變數的設置。
建立系統變數:JAVA_HOME=D:\Program Files\Java\jdk1.6.0_07;
建立系統變數:CLASSPATH=.;(逗號+分號);
編輯path系統變數:在最前面加上%JAVA_HOME%\bin;(分號)。

⑧ 如何使用Java API操作Hbase

先導入hbase的相關jar包。

再根據api進行操作。

package com.util;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
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.MasterNotRunningException;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.ZooKeeperConnectionException;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;
import org.apache.hadoop.hbase.client.Delete;
import org.apache.hadoop.hbase.client.Get;
import org.apache.hadoop.hbase.client.HBaseAdmin;
import org.apache.hadoop.hbase.client.HTable;
import org.apache.hadoop.hbase.client.HTablePool;
import org.apache.hadoop.hbase.client.Put;
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.client.Table;
import org.apache.hadoop.hbase.filter.CompareFilter.CompareOp;
import org.apache.hadoop.hbase.filter.Filter;
import org.apache.hadoop.hbase.filter.FilterList;
import org.apache.hadoop.hbase.filter.SingleColumnValueFilter;
import org.apache.hadoop.hbase.util.Bytes;
public class HBaseUtil {
public static Configuration configuration;
static {
configuration = HBaseConfiguration.create();
configuration.set("hbase.zookeeper.property.clientPort", "2181");
configuration.set("hbase.zookeeper.quorum", "192.168.1.103");
configuration.set("hbase.master", "192.168.1.103:600000");
}

public static void main(String[] args) throws IOException {
createTable("abc");
insertData("abc");
QueryAll("abc");
}

/**
* 創建表
* @param tableName
*/
public static void createTable(String tableName) {
System.out.println("start create table ......");
try {
HBaseAdmin hBaseAdmin = new HBaseAdmin(configuration);
if (hBaseAdmin.tableExists(tableName)) {// 如果存在要創建的表,那麼先刪除,再創建
hBaseAdmin.disableTable(tableName);
hBaseAdmin.deleteTable(tableName);
System.out.println(tableName + " is exist,detele....");
}
HTableDescriptor tableDescriptor = new HTableDescriptor(TableName.valueOf(tableName));
tableDescriptor.addFamily(new HColumnDescriptor("column1"));
tableDescriptor.addFamily(new HColumnDescriptor("column2"));
tableDescriptor.addFamily(new HColumnDescriptor("column3"));
hBaseAdmin.createTable(tableDescriptor);

hBaseAdmin.close();
} catch (MasterNotRunningException e) {
e.printStackTrace();
} catch (ZooKeeperConnectionException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("end create table ......");
}

/**
* 插入數據
* @param tableName
* @throws IOException
*/
public static void insertData(String tableName) throws IOException {
System.out.println("start insert data ......");
Connection connection = ConnectionFactory.createConnection(configuration);
Table table = connection.getTable(TableName.valueOf(tableName));
Put put = new Put("112233bbbcccc".getBytes());// 一個PUT代表一行數據,再NEW一個PUT表示第二行數據,每行一個唯一的ROWKEY,此處rowkey為put構造方法中傳入的值
put.add("column1".getBytes(), null, "aaa".getBytes());// 本行數據的第一列
put.add("column2".getBytes(), null, "bbb".getBytes());// 本行數據的第三列
put.add("column3".getBytes(), null, "ccc".getBytes());// 本行數據的第三列
try {
table.put(put);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("end insert data ......");
}

/**
* 刪除一張表
* @param tableName
*/
public static void dropTable(String tableName) {
try {
HBaseAdmin admin = new HBaseAdmin(configuration);
admin.disableTable(tableName);
admin.deleteTable(tableName);
} catch (MasterNotRunningException e) {
e.printStackTrace();
} catch (ZooKeeperConnectionException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

}
/**
* 根據 rowkey刪除一條記錄
* @param tablename
* @param rowkey
*/
public static void deleteRow(String tablename, String rowkey) {
try {
HTable table = new HTable(configuration, tablename);
List list = new ArrayList();
Delete d1 = new Delete(rowkey.getBytes());
list.add(d1);

table.delete(list);
System.out.println("刪除行成功!");

} catch (IOException e) {
e.printStackTrace();
}

}

/**
* 組合條件刪除
* @param tablename
* @param rowkey
*/
public static void deleteByCondition(String tablename, String rowkey) {
//目前還沒有發現有效的API能夠實現 根據非rowkey的條件刪除 這個功能能,還有清空表全部數據的API操作

}

/**
* 查詢所有數據
* @param tableName
* @throws IOException
*/
public static void QueryAll(String tableName) throws IOException {
Connection connection = ConnectionFactory.createConnection(configuration);
Table table = connection.getTable(TableName.valueOf(tableName));
try {
ResultScanner rs = table.getScanner(new Scan());
for (Result r : rs) {
System.out.println("獲得到rowkey:" + new String(r.getRow()));
for (KeyValue keyValue : r.raw()) {
System.out.println("列:" + new String(keyValue.getFamily())
+ "====值:" + new String(keyValue.getValue()));
}
}
} catch (IOException e) {
e.printStackTrace();
}
}

/**
* 單條件查詢,根據rowkey查詢唯一一條記錄
* @param tableName
*/
public static void QueryByCondition1(String tableName) {

HTablePool pool = new HTablePool(configuration, 1000);
HTable table = (HTable) pool.getTable(tableName);
try {
Get scan = new Get("abcdef".getBytes());// 根據rowkey查詢
Result r = table.get(scan);
System.out.println("獲得到rowkey:" + new String(r.getRow()));
for (KeyValue keyValue : r.raw()) {
System.out.println("列:" + new String(keyValue.getFamily())
+ "====值:" + new String(keyValue.getValue()));
}
} catch (IOException e) {
e.printStackTrace();
}
}

/**
* 單條件按查詢,查詢多條記錄
* @param tableName
*/
public static void QueryByCondition2(String tableName) {

try {
HTablePool pool = new HTablePool(configuration, 1000);
HTable table = (HTable) pool.getTable(tableName);
Filter filter = new SingleColumnValueFilter(Bytes
.toBytes("column1"), null, CompareOp.EQUAL, Bytes
.toBytes("aaa")); // 當列column1的值為aaa時進行查詢
Scan s = new Scan();
s.setFilter(filter);
ResultScanner rs = table.getScanner(s);
for (Result r : rs) {
System.out.println("獲得到rowkey:" + new String(r.getRow()));
for (KeyValue keyValue : r.raw()) {
System.out.println("列:" + new String(keyValue.getFamily())
+ "====值:" + new String(keyValue.getValue()));
}
}
} catch (Exception e) {
e.printStackTrace();
}

}

/**
* 組合條件查詢
* @param tableName
*/
public static void QueryByCondition3(String tableName) {

try {
HTablePool pool = new HTablePool(configuration, 1000);
HTable table = (HTable) pool.getTable(tableName);

List<Filter> filters = new ArrayList<Filter>();

Filter filter1 = new SingleColumnValueFilter(Bytes
.toBytes("column1"), null, CompareOp.EQUAL, Bytes
.toBytes("aaa"));
filters.add(filter1);

Filter filter2 = new SingleColumnValueFilter(Bytes
.toBytes("column2"), null, CompareOp.EQUAL, Bytes
.toBytes("bbb"));
filters.add(filter2);

Filter filter3 = new SingleColumnValueFilter(Bytes
.toBytes("column3"), null, CompareOp.EQUAL, Bytes
.toBytes("ccc"));
filters.add(filter3);

FilterList filterList1 = new FilterList(filters);

Scan scan = new Scan();
scan.setFilter(filterList1);
ResultScanner rs = table.getScanner(scan);
for (Result r : rs) {
System.out.println("獲得到rowkey:" + new String(r.getRow()));
for (KeyValue keyValue : r.raw()) {
System.out.println("列:" + new String(keyValue.getFamily())
+ "====值:" + new String(keyValue.getValue()));
}
}
rs.close();

} catch (Exception e) {
e.printStackTrace();
}

}

}

⑨ 如何使用Java API讀寫Hbase

一般情況下,我們使用Linux的shell命令,就可以非常輕松的操作Hbase,例如一些建表,建列簇,插值,顯示所有表,統計數量等等,但有時為了提高靈活性,我們也需要使用編程語言來操作Hbase,當然Hbase通過Thrift介面提供了對大多數主流編程語言的支持,例如C++,PHP,Python,Ruby等等,那麼本篇,散仙給出的例子是基於Java原生的API操作Hbase,相比其他的一些編程語言,使用Java操作Hbase,會更加高效一些,因為Hbase本身就是使用Java語言編寫的。轉載
下面,散仙給出源碼,以供參考:

package com.hbase;

import java.util.ArrayList;
import java.util.List;

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.Delete;
import org.apache.hadoop.hbase.client.Get;
import org.apache.hadoop.hbase.client.HBaseAdmin;
import org.apache.hadoop.hbase.client.HTable;
import org.apache.hadoop.hbase.client.Put;
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.util.Bytes;

/**
* @author 三劫散仙
*
* **/
public class Test {

static Configuration conf=null;
static{

conf=HBaseConfiguration.create();//hbase的配置信息
conf.set("hbase.zookeeper.quorum", "10.2.143.5"); //zookeeper的地址

}

public static void main(String[] args)throws Exception {

Test t=new Test();
//t.createTable("temp", new String[]{"name","age"});
//t.insertRow("temp", "2", "age", "myage", "100");
// t.getOneDataByRowKey("temp", "2");
t.showAll("temp");

}

/***
* 創建一張表
* 並指定列簇
* */
public void createTable(String tableName,String cols[])throws Exception{
HBaseAdmin admin=new HBaseAdmin(conf);//客戶端管理工具類
if(admin.tableExists(tableName)){
System.out.println("此表已經存在.......");
}else{
HTableDescriptor table=new HTableDescriptor(tableName);
for(String c:cols){
HColumnDescriptor col=new HColumnDescriptor(c);//列簇名
table.addFamily(col);//添加到此表中
}

admin.createTable(table);//創建一個表
admin.close();
System.out.println("創建表成功!");
}
}

/**
* 添加數據,
* 建議使用批量添加
* @param tableName 表名
* @param row 行號
* @param columnFamily 列簇
* @param column 列
* @param value 具體的值
*
* **/
public void insertRow(String tableName, String row,
String columnFamily, String column, String value) throws Exception {
HTable table = new HTable(conf, tableName);
Put put = new Put(Bytes.toBytes(row));
// 參數出分別:列族、列、值
put.add(Bytes.toBytes(columnFamily), Bytes.toBytes(column),
Bytes.toBytes(value));

table.put(put);
table.close();//關閉
System.out.println("插入一條數據成功!");
}

/**
* 刪除一條數據
* @param tableName 表名
* @param row rowkey
* **/
public void deleteByRow(String tableName,String rowkey)throws Exception{
HTable h=new HTable(conf, tableName);
Delete d=new Delete(Bytes.toBytes(rowkey));
h.delete(d);//刪除一條數據
h.close();
}

/**
* 刪除多條數據
* @param tableName 表名
* @param row rowkey
* **/
public void deleteByRow(String tableName,String rowkey[])throws Exception{
HTable h=new HTable(conf, tableName);

List<Delete> list=new ArrayList<Delete>();
for(String k:rowkey){
Delete d=new Delete(Bytes.toBytes(k));
list.add(d);
}
h.delete(list);//刪除
h.close();//釋放資源
}

/**
* 得到一條數據
*
* @param tableName 表名
* @param rowkey 行號
* ***/
public void getOneDataByRowKey(String tableName,String rowkey)throws Exception{
HTable h=new HTable(conf, tableName);

Get g=new Get(Bytes.toBytes(rowkey));
Result r=h.get(g);
for(KeyValue k:r.raw()){

System.out.println("行號: "+Bytes.toStringBinary(k.getRow()));
System.out.println("時間戳: "+k.getTimestamp());
System.out.println("列簇: "+Bytes.toStringBinary(k.getFamily()));
System.out.println("列: "+Bytes.toStringBinary(k.getQualifier()));
//if(Bytes.toStringBinary(k.getQualifier()).equals("myage")){
// System.out.println("值: "+Bytes.toInt(k.getValue()));
//}else{
String ss= Bytes.toString(k.getValue());
System.out.println("值: "+ss);
//}

}
h.close();

}

/**
* 掃描所有數據或特定數據
* @param tableName
* **/
public void showAll(String tableName)throws Exception{

HTable h=new HTable(conf, tableName);

Scan scan=new Scan();
//掃描特定區間
//Scan scan=new Scan(Bytes.toBytes("開始行號"),Bytes.toBytes("結束行號"));
ResultScanner scanner=h.getScanner(scan);
for(Result r:scanner){
System.out.println("==================================");
for(KeyValue k:r.raw()){

System.out.println("行號: "+Bytes.toStringBinary(k.getRow()));
System.out.println("時間戳: "+k.getTimestamp());
System.out.println("列簇: "+Bytes.toStringBinary(k.getFamily()));
System.out.println("列: "+Bytes.toStringBinary(k.getQualifier()));
//if(Bytes.toStringBinary(k.getQualifier()).equals("myage")){
// System.out.println("值: "+Bytes.toInt(k.getValue()));
//}else{
String ss= Bytes.toString(k.getValue());
System.out.println("值: "+ss);
//}

}
}
h.close();

}

}

顯示所有數據的列印輸出如下:

==================================
行號: 1
時間戳: 1385597699287
列簇: name
列: myname
值: 秦東亮
==================================
行號: 2
時間戳: 1385598393306
列簇: age
列: myage
值: 100
行號: 2
時間戳: 1385597723900
列簇: name
列: myname
值: 三劫散仙

由此,可以看出Hbase的對外的API提供介面,是非常簡單易用的

⑩ 如何使用Java API操作Hbase

代碼如下:

package com.dhgate.hbase.test;

import java.util.ArrayList;
import java.util.List;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.CellUtil;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Delete;
import org.apache.hadoop.hbase.client.Get;
import org.apache.hadoop.hbase.client.HBaseAdmin;
import org.apache.hadoop.hbase.client.HTable;
import org.apache.hadoop.hbase.client.Put;
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.filter.PageFilter;
import org.apache.hadoop.hbase.filter.PrefixFilter;
import org.apache.hadoop.hbase.util.Bytes;

/**
* 基於新的API
* Hbase0.96版本
* 寫的工具類
*
* @author qindongliang
* 大數據技術交流群: 376932160
*
* **/
public class HbaseCommons {

static Configuration conf=HBaseConfiguration.create();
static String tableName="";

public static void main(String[] args)throws Exception {

//String tableName="test";
//createTable(tableName, null);

}

/**
* 批量添加數據
* @param tableName 標名字
* @param rows rowkey行健的集合
* 本方法僅作示例,其他的內容需要看自己義務改變
*
* **/
public static void insertList(String tableName,String rows[])throws Exception{
HTable table=new HTable(conf, tableName);
List<Put> list=new ArrayList<Put>();
for(String r:rows){
Put p=new Put(Bytes.toBytes(r));
//此處示例添加其他信息
//p.add(Bytes.toBytes("family"),Bytes.toBytes("column"), 1000, Bytes.toBytes("value"));
list.add(p);
}
table.put(list);//批量添加
table.close();//釋放資源
}

/**
* 創建一個表
* @param tableName 表名字
* @param columnFamilys 列簇
*
* **/
public static void createTable(String tableName,String[] columnFamilys)throws Exception{
//admin 對象
HBaseAdmin admin=new HBaseAdmin(conf);
if(admin.tableExists(tableName)){
System.out.println("此表,已存在!");
}else{
//舊的寫法
//HTableDescriptor tableDesc=new HTableDescriptor(tableName);
//新的api
HTableDescriptor tableDesc=new HTableDescriptor(TableName.valueOf(tableName));

for(String columnFamily:columnFamilys){
tableDesc.addFamily(new HColumnDescriptor(columnFamily));
}

admin.createTable(tableDesc);
System.out.println("建表成功!");

}
admin.close();//關閉釋放資源

}

/**
* 刪除一個表
* @param tableName 刪除的表名
* */
public static void deleteTable(String tableName)throws Exception{
HBaseAdmin admin=new HBaseAdmin(conf);
if(admin.tableExists(tableName)){
admin.disableTable(tableName);//禁用表
admin.deleteTable(tableName);//刪除表
System.out.println("刪除表成功!");
}else{
System.out.println("刪除的表不存在!");
}
admin.close();
}

/**
* 插入一條數據
* @param tableName 表明
* @param columnFamily 列簇
* @param column 列
* @param value 值
*
* ***/
public static void insertOneRow(String tableName,String rowkey,String columnFamily,String column,String value)throws Exception{

HTable table=new HTable(conf, tableName);
Put put=new Put(Bytes.toBytes(rowkey));
put.add(Bytes.toBytes(columnFamily), Bytes.toBytes(column), Bytes.toBytes(value));
table.put(put);//放入表
table.close();//釋放資源

}

/**
* 刪除一條數據
* @param tableName 表名
* @param row rowkey行鍵
*
* */
public static void deleteOneRow(String tableName,String row)throws Exception{

HTable table=new HTable(conf, tableName);
Delete delete=new Delete(Bytes.toBytes(row));
table.delete(delete);
table.close();
}

/**
* 刪除多條數據
* @param tableName 表名
* @param rows 行健集合
*
* **/
public static void deleteList(String tableName,String rows[])throws Exception{
HTable table=new HTable(conf, tableName);
List<Delete> list=new ArrayList<Delete>();
for(String row:rows){
Delete del=new Delete(Bytes.toBytes(row));
list.add(del);
}
table.delete(list);
table.close();//釋放資源

}

/**
* 獲取一條數據,根據rowkey
* @param tableName 表名
* @param row 行健
*
* **/
public static void getOneRow(String tableName,String row)throws Exception{
HTable table=new HTable(conf, tableName);
Get get=new Get(Bytes.toBytes(row));
Result result=table.get(get);
printRecoder(result);//列印記錄
table.close();//釋放資源
}

/**
* 查看某個表下的所有數據
*
* @param tableName 表名
* */
public static void showAll(String tableName)throws Exception{
HTable table=new HTable(conf, tableName);
Scan scan=new Scan();
ResultScanner rs=table.getScanner(scan);
for(Result r:rs){
printRecoder(r);//列印記錄
}
table.close();//釋放資源
}

/**
* 查看某個表下的所有數據
*
* @param tableName 表名
* @param rowKey 行健
* */
public static void ScanPrefixByRowKey(String tableName,String rowKey)throws Exception{
HTable table=new HTable(conf, tableName);
Scan scan=new Scan();
scan.setFilter(new PrefixFilter(Bytes.toBytes(rowKey)));
ResultScanner rs=table.getScanner(scan);
for(Result r:rs){
printRecoder(r);//列印記錄
}
table.close();//釋放資源
}

/**
* 查看某個表下的所有數據
*
* @param tableName 表名
* @param rowKey 行健掃描
* @param limit 限制返回數據量
* */
public static void ScanPrefixByRowKeyAndLimit(String tableName,String rowKey,long limit)throws Exception{
HTable table=new HTable(conf, tableName);
Scan scan=new Scan();
scan.setFilter(new PrefixFilter(Bytes.toBytes(rowKey)));
scan.setFilter(new PageFilter(limit));
ResultScanner rs=table.getScanner(scan);
for(Result r:rs){
printRecoder(r);//列印記錄
}
table.close();//釋放資源
}

/**
* 根據rowkey掃描一段范圍
* @param tableName 表名
* @param startRow 開始的行健
* @param stopRow 結束的行健
* **/
public void scanByStartAndStopRow(String tableName,String startRow,String stopRow)throws Exception{
HTable table=new HTable(conf, tableName);
Scan scan=new Scan();
scan.setStartRow(Bytes.toBytes(startRow));
scan.setStopRow(Bytes.toBytes(stopRow));
ResultScanner rs=table.getScanner(scan);
for(Result r:rs){
printRecoder(r);
}
table.close();//釋放資源

}
/**
* 掃描整個表裡面具體的某個欄位的值
* @param tableName 表名
* @param columnFalimy 列簇
* @param column 列
* **/
public static void getValueDetail(String tableName,String columnFalimy,String column)throws Exception{

HTable table=new HTable(conf, tableName);
Scan scan=new Scan();
ResultScanner rs=table.getScanner(scan);
for(Result r:rs){
System.out.println("值: " +new String(r.getValue(Bytes.toBytes(columnFalimy), Bytes.toBytes(column))));
}
table.close();//釋放資源

}

/**
* 列印一條記錄的詳情
*
* */
public static void printRecoder(Result result)throws Exception{
for(Cell cell:result.rawCells()){
System.out.print("行健: "+new String(CellUtil.cloneRow(cell)));
System.out.print("列簇: "+new String(CellUtil.cloneFamily(cell)));
System.out.print(" 列: "+new String(CellUtil.cloneQualifier(cell)));
System.out.print(" 值: "+new String(CellUtil.cloneValue(cell)));
System.out.println("時間戳: "+cell.getTimestamp());
}
}

}

閱讀全文

與hbasejava基本操作相關的資料

熱點內容
如何提高網路扶貧的效果 瀏覽:654
飛車軟體文件夾叫什麼 瀏覽:242
刷ec用什麼編程器 瀏覽:765
方菱數控u盤文件格式 瀏覽:260
編程為什麼輸出兩個變數 瀏覽:490
衛星大鍋2017用升級嗎 瀏覽:113
玉米win10系統下載 瀏覽:134
fgo技能升級減cd嗎 瀏覽:129
什麼記賬app免費好用 瀏覽:441
網路檢測可以檢測到什麼 瀏覽:504
sip協議教程 瀏覽:832
編程哪裡可以接項目 瀏覽:119
孤島驚魂win10 瀏覽:246
網路HRV是什麼意思 瀏覽:918
word框中打勾 瀏覽:577
tcl筆試題java 瀏覽:467
win10怎麼登錄安全模式 瀏覽:679
除了archdaily還有什麼網站 瀏覽:567
數控下料圓形怎麼編程 瀏覽:785
安裝游戲在文件管理找不到怎麼辦 瀏覽:216

友情鏈接