⑴ 如何使用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());
}
}
}
⑵ hbase java端調用
這是缺少必要的類org/apache/hadoop/thirdparty/guava/common/primitives/UnsignedBytes
你可以到jarsearch上搜索含有這個類的jar包,然後把它放到classpath下就行了
⑶ 如何使用Java API操作Hbase
java API草錯hbase舉例如下:
例如輸出表「users」的列族名稱
import java.io.IOException;
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.client.HBaseAdmin;
import org.apache.hadoop.hbase.util.Bytes;
public class ExampleClient {
public static void main(String[] args) throws IOException {
Configuration conf = HBaseConfiguration.create();
conf.set("hbase.zookeeper.quorum", "master");//使用eclipse時必須添加這個,否則無法定位
conf.set("hbase.zookeeper.property.clientPort", "2181");
HBaseAdmin admin = new HBaseAdmin(conf);// 新建一個資料庫管理員
HTableDescriptor tableDescriptor = admin.getTableDescriptor(Bytes.toBytes("users"));
byte[] name = tableDescriptor.getName();
System.out.println("result:");
System.out.println("table name: "+ new String(name));
HColumnDescriptor[] columnFamilies = tableDescriptor
.getColumnFamilies();
for(HColumnDescriptor d : columnFamilies){
System.out.println("column Families: "+ d.getNameAsString());
}
}
}
輸出結果:
2013-09-09 15:58:51,890 WARN conf.Configuration (Configuration.java:<clinit>(195)) - DEPRECATED: hadoop-site.xml found in the classpath. Usage of hadoop-site.xml is deprecated. Instead use core-site.xml, mapred-site.xml and hdfs-site.xml to override properties of core-default.xml, mapred-default.xml and hdfs-default.xml respectively
2013-09-09 15:58:55,031 INFO zookeeper.ZooKeeper (Environment.java:logEnv(100)) - Client environment:zookeeper.version=3.4.5-1392090, built on 09/30/2012 17:52 GMT
2013-09-09 15:58:55,031 INFO zookeeper.ZooKeeper (Environment.java:logEnv(100)) - Client environment:host.name=w253245.ppp.asahi-net.or.jp
2013-09-09 15:58:55,031 INFO zookeeper.ZooKeeper (Environment.java:logEnv(100)) - Client environment:java.version=1.6.0_10-rc2
2013-09-09 15:58:55,031 INFO zookeeper.ZooKeeper (Environment.java:logEnv(100)) - Client environment:java.vendor=Sun Microsystems Inc.
2013-09-09 15:58:55,031 INFO zookeeper.ZooKeeper (Environment.java:logEnv(100)) - Client environment:java.home=C:\Java\jre6
2013-09-09 15:58:55,031 INFO zookeeper.ZooKeeper (Environment.java:logEnv(100)) - Client environment:java.class.path
2013-09-09 15:58:55,031 INFO zookeeper.ZooKeeper (Environment.java:logEnv(100)) - Client environment:java.library.path=D:\workspace\Eclipse-jee\hadoop-1.1.21\lib\native;D:\workspace\Eclipse-jee\hadoop-1.1.21\lib\native
2013-09-09 15:58:55,031 INFO zookeeper.ZooKeeper (Environment.java:logEnv(100)) - Client environment:java.io.tmpdir=C:\DOCUME~1\ADMINI~1\LOCALS~1\Temp\
2013-09-09 15:58:55,031 INFO zookeeper.ZooKeeper (Environment.java:logEnv(100)) - Client environment:java.compiler=<NA>
2013-09-09 15:58:55,031 INFO zookeeper.ZooKeeper (Environment.java:logEnv(100)) - Client environment:os.name=Windows XP
2013-09-09 15:58:55,031 INFO zookeeper.ZooKeeper (Environment.java:logEnv(100)) - Client environment:os.arch=x86
2013-09-09 15:58:55,031 INFO zookeeper.ZooKeeper (Environment.java:logEnv(100)) - Client environment:os.version=5.1
2013-09-09 15:58:55,031 INFO zookeeper.ZooKeeper (Environment.java:logEnv(100)) - Client environment:user.name=hadoop
2013-09-09 15:58:55,031 INFO zookeeper.ZooKeeper (Environment.java:logEnv(100)) - Client environment:user.home=C:\Documents and Settings\Administrator
2013-09-09 15:58:55,031 INFO zookeeper.ZooKeeper (Environment.java:logEnv(100)) - Client environment:user.dir=D:\workspace\Eclipse-jee\Hadoop_APPs_U_tht
2013-09-09 15:58:55,031 INFO zookeeper.ZooKeeper (ZooKeeper.java:<init>(438)) - Initiating client connection, connectString=master:2181 sessionTimeout=180000 watcher=hconnection
2013-09-09 15:58:56,171 INFO zookeeper.RecoverableZooKeeper (RecoverableZooKeeper.java:<init>(104)) - The identifier of this process is 6032@tht
2013-09-09 15:58:56,234 INFO zookeeper.ClientCnxn (ClientCnxn.java:logStartConnect(966)) - Opening socket connection to server master/121.1.253.251:2181. Will not attempt to authenticate using SASL (無法定位登錄配置)
2013-09-09 15:58:56,296 INFO zookeeper.ClientCnxn (ClientCnxn.java:primeConnection(849)) - Socket connection established to master/121.1.253.251:2181, initiating session
2013-09-09 15:58:56,484 INFO zookeeper.ClientCnxn (ClientCnxn.java:onConnected(1207)) - Session establishment complete on server master/121.1.253.251:2181, sessionid = 0x141011ad7db000e, negotiated timeout = 180000
result:
table name: users
column Families: address
column Families: info
column Families: user_id
⑷ 如何使用Java API操作Hbase
使用Linux的shell命令,就可以非常輕松的操作Hbase,例如一些建表,建列簇,插值,顯示所有表,統計數量等等,但有時為了提高靈活性,我們也需要使用編程語言來操作Hbase
當然Hbase通過Thrift介面提供了對大多數主流編程語言的支持,例如C++,PHP,Python,Ruby等等,那麼本篇,散仙給出的例子是基於Java原生的API操作Hbase,相比其他的一些編程語言,使用Java操作Hbase,會更加高效一些,因為Hbase本身就是使用Java語言編寫的。
⑸ 如何使用Java API操作Hbase
HBase提供了對HBase進行一系列的管理涉及到對表的管理、數據的操作java api。
常用的API操作有:
1、 對表的創建、刪除、顯示以及修改等,可以用HBaseAdmin,一旦創建了表,那麼可以通過HTable的實例來訪問表,每次可以往表裡增加數據。
2、 插入數據
創建一個Put對象,在這個Put對象里可以指定要給哪個列增加數據,以及當前的時間戳等值,然後通過調用HTable.put(Put)來提交操作,子猴在這里提請注意的是:在創建Put對象的時候,你必須指定一個行(Row)值,在構造Put對象的時候作為參數傳入。
3、 獲取數據
要獲取數據,使用Get對象,Get對象同Put對象一樣有好幾個構造函數,通常在構造的時候傳入行值,表示取第幾行的數據,通過HTable.get(Get)來調用。
4、 瀏覽每一行
通過Scan可以對表中的行進行瀏覽,得到每一行的信息,比如列名,時間戳等,Scan相當於一個游標,通過next()來瀏覽下一個,通過調用HTable.getScanner(Scan)來返回一個ResultScanner對象。HTable.get(Get)和HTable.getScanner(Scan)都是返回一個Result。Result是一個
KeyValue的鏈表。
5、 刪除
使用Delete來刪除記錄,通過調用HTable.delete(Delete)來執行刪除操作。(註:刪除這里有些特別,也就是刪除並不是馬上將數據從表中刪除。)
6、 鎖
新增、獲取、刪除在操作過程中會對所操作的行加一個鎖,而瀏覽卻不會。
7、 簇的訪問
客戶端代碼通過ZooKeeper來訪問找到簇,也就是說ZooKeeper quorum將被使用,那麼相關的類(包)應該在客戶端的類(classes)目錄下,即客戶端一定要找到文件hbase-site.xml。
下面是一個例子程序:
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.ZooKeeperConnectionException;
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.Result;
import org.apache.hadoop.hbase.client.ResultScanner;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.util.Bytes;
public class HBaseTest {
private static Configuration conf = null;
/**
* 初始化配置
*/
static {
Configuration HBASE_CONFIG = new Configuration();
//與hbase/conf/hbase-site.xml中hbase.zookeeper.quorum配置的值相同
HBASE_CONFIG.set("hbase.zookeeper.quorum", "10.1.1.1");
//與hbase/conf/hbase-site.xml中hbase.zookeeper.property.clientPort配置的值相同
HBASE_CONFIG.set("hbase.zookeeper.property.clientPort", "2181");
conf = HBaseConfiguration.create(HBASE_CONFIG);
}
/**
* 創建一張表
*/
public static void creatTable(String tableName, String[] familys) throws Exception {
HBaseAdmin admin = new HBaseAdmin(conf);
if (admin.tableExists(tableName)) {
System.out.println("table already exists!");
} else {
HTableDescriptor tableDesc = new HTableDescriptor(tableName);
for(int i=0; i<familys.length; i++){
tableDesc.addFamily(new HColumnDescriptor(familys[i]));
}
admin.createTable(tableDesc);
System.out.println("create table " + tableName + " ok.");
}
}
/**
* 刪除表
*/
public static void deleteTable(String tableName) throws Exception {
try {
HBaseAdmin admin = new HBaseAdmin(conf);
admin.disableTable(tableName);
admin.deleteTable(tableName);
System.out.println("delete table " + tableName + " ok.");
} catch (MasterNotRunningException e) {
e.printStackTrace();
} catch (ZooKeeperConnectionException e) {
e.printStackTrace();
}
}
/**
* 插入一行記錄
*/
public static void addRecord (String tableName, String rowKey, String family, String qualifier, String value)
throws Exception{
try {
HTable table = new HTable(conf, tableName);
Put put = new Put(Bytes.toBytes(rowKey));
put.add(Bytes.toBytes(family),Bytes.toBytes(qualifier),Bytes.toBytes(value));
table.put(put);
System.out.println("insert recored " + rowKey + " to table " + tableName +" ok.");
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 刪除一行記錄
*/
public static void delRecord (String tableName, String rowKey) throws IOException{
HTable table = new HTable(conf, tableName);
List list = new ArrayList();
Delete del = new Delete(rowKey.getBytes());
list.add(del);
table.delete(list);
System.out.println("del recored " + rowKey + " ok.");
}
/**
* 查找一行記錄
*/
public static void getOneRecord (String tableName, String rowKey) throws IOException{
HTable table = new HTable(conf, tableName);
Get get = new Get(rowKey.getBytes());
Result rs = table.get(get);
for(KeyValue kv : rs.raw()){
System.out.print(new String(kv.getRow()) + " " );
System.out.print(new String(kv.getFamily()) + ":" );
System.out.print(new String(kv.getQualifier()) + " " );
System.out.print(kv.getTimestamp() + " " );
System.out.println(new String(kv.getValue()));
}
}
/**
* 顯示所有數據
*/
public static void getAllRecord (String tableName) {
try{
HTable table = new HTable(conf, tableName);
Scan s = new Scan();
ResultScanner ss = table.getScanner(s);
for(Result r:ss){
for(KeyValue kv : r.raw()){
System.out.print(new String(kv.getRow()) + " ");
System.out.print(new String(kv.getFamily()) + ":");
System.out.print(new String(kv.getQualifier()) + " ");
System.out.print(kv.getTimestamp() + " ");
System.out.println(new String(kv.getValue()));
}
}
} catch (IOException e){
e.printStackTrace();
}
}
public static void main (String [] agrs) {
try {
String tablename = "scores";
String[] familys = {"grade", "course"};
HBaseTest.creatTable(tablename, familys);
//add record zkb
HBaseTest.addRecord(tablename,"zkb","grade","","5");
HBaseTest.addRecord(tablename,"zkb","course","","90");
HBaseTest.addRecord(tablename,"zkb","course","math","97");
HBaseTest.addRecord(tablename,"zkb","course","art","87");
//add record baoniu
HBaseTest.addRecord(tablename,"baoniu","grade","","4");
HBaseTest.addRecord(tablename,"baoniu","course","math","89");
System.out.println("===========get one record========");
HBaseTest.getOneRecord(tablename, "zkb");
System.out.println("===========show all record========");
HBaseTest.getAllRecord(tablename);
System.out.println("===========del one record========");
HBaseTest.delRecord(tablename, "baoniu");
HBaseTest.getAllRecord(tablename);
System.out.println("===========show all record========");
HBaseTest.getAllRecord(tablename);
} catch (Exception e) {
e.printStackTrace();
}
}
}
⑹ 北大青鳥java培訓:Hbase知識點總結
hbase概念:非結構化的分布式的面向列存儲非關系型的開源的資料庫,根據谷歌的三大論文之一的bigtable高寬厚表作用:為了解決大規模數據集合多重數據種類帶來的挑戰,尤其是大數據應用難題。
能幹什麼:存儲大量結果集數據,低延遲的隨機查詢。
sql:結構化查詢語言nosql:非關系型資料庫,列存儲和文檔存儲(查詢低延遲),hbase是nosql的一個種類,其特點是列式存儲。
非關系型資料庫--列存儲(hbase)非關系型資料庫--文檔存儲(MongoDB)非關系型資料庫--內存式存儲(redis)非關系型資料庫--圖形模型(graph)hive和hbase區別?Hive的定位是數據倉庫,雖然也有增刪改查,但其刪改查對應的是整張表而不是單行數據,查詢的延遲較高。
其本質是更加方便的使用mr的威力來進行離線分析的一個數據分析工具。
HBase的定位是hadoop的資料庫,電腦培訓http://www.kmbdqn.cn/發現是一個典型的Nosql,所以HBase是用來在大量數據中進行低延遲的隨機查詢的。
hbase運行方式:standalonedistrubited單節點和偽分布式?單節點:單獨的進程運行在同一台機器上hbase應用場景:存儲海量數據低延遲查詢數據hbase表由多行組成hbase行一行在hbase中由行健和一個或多個列的值組成,按行健字母順序排序的存儲。
⑺ 如何使用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
一般情況下,我們使用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
值: