java 对Hbase的基本操作

Java对Hbase的各种操作都是通过HTable实现的,由于创建HTable是有消耗的,因此推荐只创建一个HTable的实例,如果必须使用多个HTable实例,可以使用HTablePool,本文不对HTablePool进行介绍。

创建表:

创建表是通过HBaseAdmin类实现的,通过HBaseAdmin 类主要是对于表的管理操作。

 1 public static void createTable(String tableName, String[] cfs) throws IOException{
 2         HBaseAdmin admin = new HBaseAdmin(configuration);
 3         if (admin.tableExists(tableName)) {
 4             System.out.println("table already exists");
 5         }else {
 6             HTableDescriptor descriptor = new HTableDescriptor(tableName);
 7             for(int i = 0; i < cfs.length; ++i){
 8                 descriptor.addFamily(new HColumnDescriptor(cfs[i]));
 9             }
10             admin.createTable(descriptor);
11         }
12     }

HBaseAdmin还包含了各种操作表的API,包括删除表,删除列等,有兴趣的可以看他的官方API,这里就不再讨论了。

添加数据:

添加数据通过HTable的put操作,添加Put对象;

void put(Put put) throws IOException

对于Put类,包含了多个构造函数使用,在这里我们只是使用了他的第一个构造函数。

Put(byte[] row)
Put(byte[] row, RowLock rowLock)
Put(byte[] row, long ts)
Put(byte[] row, long ts, RowLock rowLock)

像Put对象添加数据使用add函数:

Put add(byte[] family, byte[] qualifier, byte[] value)
Put add(byte[] family, byte[] qualifier, long ts, byte[] value)
Put add(KeyValue kv) throws IOException

添加数据操作:

1 public static void putData(String tableName) throws IOException{
2         HTable table = new HTable(configuration, tableName);
3         Put put = new Put(Bytes.toBytes("row1"));
4         put.add(Bytes.toBytes("cf"), Bytes.toBytes("a"), Bytes.toBytes("v1"));
5         table.put(put);
6         table.close();
7     }

获取数据:

对于获取数据,需要喜欢使用HTable的get函数:

Result get(Get get) throws IOException

Get类的构造函数相对与Put少了ts

Get(byte[] row)
Get(byte[] row, RowLock rowLock)

获取数据的操作:

1 public static void getData(String tableName) throws IOException{
2         HTable table = new HTable(configuration, tableName);
3         Get get = new Get(Bytes.toBytes("row1"));
4         Result result = table.get(get);
5         String value = new String(result.getValue(Bytes.toBytes("cf"), Bytes.toBytes("a")));
6         System.out.println(value);
7         table.close();
8     }

对于扫描全表则需要使用scanner了。

public static void scannerData(String tablename) throws IOException {
        HTable table = new HTable(configuration, tablename);
        Scan s = new Scan();
        ResultScanner rs = table.getScanner(s);
        for (Result r : rs) {
            KeyValue[] kv = r.raw();
            for (int i = 0; i < kv.length; i++) {
                System.out.print(new String(kv[i].getRow()) + "  ");
                System.out.print(new String(kv[i].getFamily()) + ":");
                System.out.print(new String(kv[i].getQualifier()) + "  ");
                System.out.print(kv[i].getTimestamp() + "  ");
                System.out.println(new String(kv[i].getValue()));
            }
        }
    }
原文地址:https://www.cnblogs.com/hitandrew/p/2882793.html