HBase基本操作-Java实现

时间:2023-03-10 01:16:20
HBase基本操作-Java实现

创建Table

 public static void createTable(String tableName){
try {
HBaseAdmin hbaseAdmin = new HBaseAdmin(HBaseConfiguration.create()); if(hbaseAdmin.tableExists(tableName)){
hbaseAdmin.disableTable(tableName);
hbaseAdmin.deleteTable(tableName);
System.out.println("Table "+ tableName +" is already exist");
} // HTableDescriptor hTableDescriptor = new HTableDescriptor(tableName);
//新版 API
HTableDescriptor hTableDescriptor = new HTableDescriptor(TableName.valueOf(tableName));
hTableDescriptor.addFamily(new HColumnDescriptor("name"));
hTableDescriptor.addFamily(new HColumnDescriptor("course"));
hTableDescriptor.addFamily(new HColumnDescriptor("address"));
hbaseAdmin.createTable(hTableDescriptor); hbaseAdmin.close();
System.out.println("Create table "+ tableName +" finish..."); } catch (IOException e) {
e.printStackTrace();
}
}

插入数据

 public static void insertDate(String tableName){
try {
HTable hTable = new HTable(HBaseConfiguration.create(),tableName);
Put putRow = null;
for(int i=1;i<=1000;i++){
putRow = new Put(("rowkey"+i).getBytes());
putRow.add("name".getBytes(), null, getNameByRandom());
putRow.add("course".getBytes(), "CHINESE".getBytes(), getScoreByRandom());
putRow.add("course".getBytes(), "ENGLISH".getBytes(), getScoreByRandom());
putRow.add("course".getBytes(), "MATH".getBytes(), getScoreByRandom());
putRow.add("address".getBytes(), "CITY".getBytes(), getNameByRandom());
putRow.add("address".getBytes(), "STREET".getBytes(), getNameByRandom());
putRow.add("address".getBytes(), "PROVINCE".getBytes(), getNameByRandom());
hTable.put(putRow);
}
hTable.close();
System.out.println("Insert finish...");
} catch (IOException e) {
e.printStackTrace();
}
} public static byte[] getScoreByRandom() {
return (((int)(Math.random()*60)+40)+"").getBytes();
} public static byte[] getNameByRandom() {
int length = (int)(Math.random()*5)+3;
String nameStr = ""+(char)((int)(Math.random()*26)+'A');
for(int i=1;i<length;i++){
char c = (char)((int)(Math.random()*26)+'a');
nameStr+=c;
}
return nameStr.getBytes();
}

查询数据

 public static void queryByRowKeyFamily(String tableName,String rowKey,String family){
try {
HTable table = new HTable(HBaseConfiguration.create(), tableName);
Get getRow = new Get(Bytes.toBytes(rowKey));
getRow.addFamily(family.getBytes());
Result result = table.get(getRow); for(KeyValue kv:result.list()){
System.out.println(new String(kv.getFamily())+"."+new String(kv.getQualifier())+" "+new String(kv.getValue()));
}
System.out.println(Bytes.toString(result.getRow()));
table.close();
} catch (IOException e) {
e.printStackTrace();
}
}