Hbase java客户端操作

时间:2022-02-19 23:23:35

1,创建表

2,put操作

public class myHbase {
    
    private static Configuration conf= null;
    static {
        conf=HBaseConfiguration.create();
    }
    /**
     * column familys add column <--->hbase columnName
     * @param tableName
     * @param familys
     * @throws Exception
     */
    public void createTable(String tableName,String[] familys) throws Exception{
        HBaseAdmin admin = new HBaseAdmin(conf);
        if(!admin.tableExists(tableName)){
            HTableDescriptor desc = new HTableDescriptor(tableName);
            for (int i = 0; i < familys.length; i++) {
                desc.addFamily(new HColumnDescriptor(familys[i]));
            }
              admin.createTable(desc);  
        }else{
            System.out.println("the table:"+ tableName +" exsists");
        };
    }
    /**
     * @param tableName
     * @param rowKey
     * @param family
     * @param qualifier
     * @param value
     * @throws Exception
     */
    public void putData(String tableName,String rowKey, String family,
            String qualifier, String value) throws Exception {
        HTable ht = new HTable(conf, tableName);
        Put put = new Put(Bytes.toBytes(rowKey));
        put.add(Bytes.toBytes(family), Bytes.toBytes(qualifier), Bytes.toBytes(value));
        ht.put(put);
    }
    public static void main(String [] agrs) throws Exception{
        myHbase h= new myHbase();
        String [] familys = {"family1","family2"};
        h.createTable("mytable", familys);
        h.putData("mytable", "row", "family1", "qualifier:name1", "value1");
    }

}


运行java应用程序:登录hbase shell 发现可以get和scan到数据了:


hbase(main):016:0> scan 'mytable'
ROW                   COLUMN+CELL                                               
 row                  column=family1:qualifier:name1, timestamp=1354559928275, v
                      alue=value1                                               
1 row(s) in 0.0410 seconds

hbase(main):017:0> get 'mytable','row','family1:qualifier:name1'
COLUMN                CELL                                                      
 family1:qualifier:na timestamp=1354559928275, value=value1                     
 me1                                                                            
1 row(s) in 0.0120 seconds