hbase 创建表、get api demo

卜高超
2023-12-01

创建表用Admin;
表查询用Table

一,创建表:

public class CreateApi {
    public static void main(String[] args) throws IOException {
        Configuration conf = HBaseConfiguration.create();
        conf.set("hbase.zookeeper.quorum","node1:2181,node2:2181,node3:2181");
        Connection connection = ConnectionFactory.createConnection(conf);

        Admin admin = connection.getAdmin();

        TableDescriptorBuilder tableDescriptorBuilder =
                TableDescriptorBuilder.newBuilder(TableName.valueOf("LCY"));
        ColumnFamilyDescriptor columnFamily = ColumnFamilyDescriptorBuilder.of("columnFamily1".getBytes(StandardCharsets.UTF_8));
        tableDescriptorBuilder.setColumnFamily(columnFamily);

        admin.createTable(tableDescriptorBuilder.build());




    }
}

二,插入数据:

public class HbaseDMLTest {
    public static void main(String[] args) throws IOException {
        Configuration conf = HBaseConfiguration.create();
        conf.set("hbase.zookeeper.quorum","node1:2181,node2:2181,node3:2181");

        Connection connection = ConnectionFactory.createConnection(conf);
        Admin admin = connection.getAdmin();

        Table lcy = connection.getTable(TableName.valueOf("LCY"));
        Put put = new Put("rk0001".getBytes(StandardCharsets.UTF_8));
        lcy.put(put.addColumn("columnFamily1".getBytes(StandardCharsets.UTF_8),"name".getBytes(StandardCharsets.UTF_8),"lcy".getBytes(StandardCharsets.UTF_8)));

        lcy.put(put);
        lcy.close();
    }
}

3,get 查询

public class HbaseQueryTest {
    public static void main(String[] args) throws IOException {
        Configuration conf = HBaseConfiguration.create();
        conf.set("hbase.zookeeper.quorum","node1:2181,node2:2181,node3:2181");

        Connection connection = ConnectionFactory.createConnection(conf);
        Admin admin = connection.getAdmin();

        Table lcy = connection.getTable(TableName.valueOf("LCY"));
        Get get = new Get("rk0001".getBytes(StandardCharsets.UTF_8));
        Result result = lcy.get(get);
        List<Cell> cells = result.listCells();
        for(Cell c : cells) {
            byte[] bytes = CellUtil.cloneFamily(c);
            byte[] bytes1 = CellUtil.cloneQualifier(c);
            byte[] bytes2 = CellUtil.cloneValue(c);

            System.out.println(new String(bytes));
            System.out.println(new String(bytes1));
            System.out.println(new String(bytes2));
        }


        lcy.close();
    }
}
 类似资料: