Hbase2.0.2之JavaAPI

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.*;
import org.apache.hadoop.hbase.filter.*;
import org.apache.hadoop.hbase.util.Bytes;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@SuppressWarnings("Duplicates")
public class HbaseJavaTwo {
    // 声明静态配置
    static Configuration conf = null;
    static Connection conn = null;
    static {
        conf = HBaseConfiguration.create();
        conf.set("hbase.zookeeper.quorum", "hadoop01,hadoop02,hadoop03");
        conf.set("hbase.zookeeper.property.clientPort", "2181");
        try {
            conn = ConnectionFactory.createConnection(conf);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static void main(String[] args) throws Exception {

        //创建表(只有一个列簇)
//        createTableOne();

        // 创建表(包含多个列簇)
        TableName tableName = TableName.valueOf("test");
        String[] columnFamilys = { "article", "author" };
//        createTable(tableName, columnFamilys);

        //添加数据
        List<Map<String,Object>> listMap=new ArrayList<Map<String, Object>>();
        Map<String,Object> map1=new HashMap<String,Object>();
        map1.put("rowKey","ce_shi1");
        map1.put("columnFamily","article");
        map1.put("columnName","title");
        map1.put("columnValue","Head First HBase");
        listMap.add(map1);
        Map<String,Object> map2=new HashMap<String,Object>();
        map2.put("rowKey","ce_shi1");
        map2.put("columnFamily","article");
        map2.put("columnName","content");
        map2.put("columnValue","HBase is the Hadoop database");
        listMap.add(map2);
        Map<String,Object> map3=new HashMap<String,Object>();
        map3.put("rowKey","ce_shi1");
        map3.put("columnFamily","article");
        map3.put("columnName","tag");
        map3.put("columnValue","Hadoop,HBase,NoSQL");
        listMap.add(map3);
        Map<String,Object> map4=new HashMap<String,Object>();
        map4.put("rowKey","ce_shi1");
        map4.put("columnFamily","author");
        map4.put("columnName","name");
        map4.put("columnValue","nicholas");
        listMap.add(map4);
        Map<String,Object> map5=new HashMap<String,Object>();
        map5.put("rowKey","ce_shi1");
        map5.put("columnFamily","author");
        map5.put("columnName","nickname");
        map5.put("columnValue","lee");
        listMap.add(map5);
        Map<String,Object> map6=new HashMap<String,Object>();
        map6.put("rowKey","ce_shi2");
        map6.put("columnFamily","author");
        map6.put("columnName","name");
        map6.put("columnValue","spark");
        listMap.add(map6);
        Map<String,Object> map7=new HashMap<String,Object>();
        map7.put("rowKey","ce_shi2");
        map7.put("columnFamily","author");
        map7.put("columnName","nickname");
        map7.put("columnValue","hadoop");
        listMap.add(map7);
//        insertMany(tableName,listMap);

        //根据RowKey,列簇,列名修改值
        String rowKey="ce_shi2";
        String columnFamily="author";
        String columnName="name";
        String columnValue="hbase";
//        updateData(tableName,rowKey,columnFamily,columnName,columnValue);


        String rowKey1="ce_shi1";
        String columnFamily1="article";
        String columnName1="name";
        List<String> columnNames=new ArrayList<String>();
        columnNames.add("content");
        columnNames.add("title");
        //删除某行某个列簇的某个列
//        deleteData(tableName,rowKey1,columnFamily1,columnName1);
        //删除某行某个列簇
//        deleteData(tableName,rowKey1,columnFamily1);
        //删除某行某个列簇的多个列
//        deleteData(tableName,rowKey1,columnFamily1,columnNames);
        //删除某行
//        deleteData(tableName,rowKey1);
        //根据rowKey查询数据
//        getResult(tableName,"rowKey1");

        //全表扫描
        scanTable(tableName);

        //rowKey过滤器
//        rowkeyFilter(tableName);

        //列值过滤器
//        singColumnFilter(tableName);

        //列名前缀过滤器
//        columnPrefixFilter(tableName);

        //过滤器集合
//        filterSet(tableName);

    }
    /**
     * 创建只有一个列簇的表
     * @throws IOException
     */

    public static void createTable() throws IOException {
        Admin admin = conn.getAdmin();
        if(!admin.tableExists(TableName.valueOf("test"))) {
            TableName tableName = TableName.valueOf("test");
            //表描述器构造器
            TableDescriptorBuilder  tdb  =TableDescriptorBuilder.newBuilder(tableName)  ;
            //列族描述起构造器
            ColumnFamilyDescriptorBuilder cdb =  ColumnFamilyDescriptorBuilder.newBuilder(Bytes.toBytes("user"));
            //获得列描述起
            ColumnFamilyDescriptor  cfd = cdb.build();
            //添加列族
            tdb.setColumnFamily(cfd);
            //获得表描述器
            TableDescriptor td = tdb.build();
            //创建表
            //admin.addColumnFamily(tableName, cfd); //给标添加列族
            admin.createTable(td);
        }else {
            System.out.println("表已存在");
        }
        //关闭链接
    }
    /**
     * 创建表(包含多个列簇)
     *
     * @tableName 表名
     *
     * @family 列族列表
     */
    public static void createTable(TableName tableName, String[] columnFamilys) throws IOException {
        Admin admin = conn.getAdmin();
        if(!admin.tableExists(tableName)) {
            //表描述器构造器
            TableDescriptorBuilder  tdb  =TableDescriptorBuilder.newBuilder(tableName)  ;
            //列族描述器构造器
            ColumnFamilyDescriptorBuilder cdb ;
            //获得列描述器
            ColumnFamilyDescriptor  cfd ;
            for (String columnFamily:columnFamilys) {
                cdb =  ColumnFamilyDescriptorBuilder.newBuilder(Bytes.toBytes(columnFamily));
                cfd = cdb.build();
                //添加列族
                tdb.setColumnFamily(cfd);
            }
            //获得表描述器
            TableDescriptor td = tdb.build();
            //创建表
            admin.createTable(td);
        }else {
            System.out.println("表已存在!");
        }
        //关闭链接
    }

    /**
     * 添加数据(多个rowKey,多个列簇,适合由固定结构的数据)
     * @param tableName
     * @param list
     * @throws IOException
     */
    public static void insertMany(TableName tableName,List<Map<String,Object>> list)
            throws IOException {
        List<Put> puts = new ArrayList<Put>();
        Table table = conn.getTable(tableName);// Tabel负责跟记录相关的操作如增删改查等//
        if(list!=null&&list.size()>0){
            for(Map<String,Object> map:list){
                Put put=new Put(Bytes.toBytes(map.get("rowKey").toString()));
                put.addColumn(Bytes.toBytes(map.get("columnFamily").toString()),
                        Bytes.toBytes(map.get("columnName").toString()),
                        Bytes.toBytes(map.get("columnValue").toString()));
                puts.add(put);
            }
        }
        table.put(puts);
        table.close();
        System.out.println("add data Success!");
    }

    /**
     * 添加数据(多个rowKey,多个列簇)
     * @throws IOException
     */
    public static void insertMany() throws IOException {
        Table table = conn.getTable(TableName.valueOf("test"));
        List<Put> puts = new ArrayList<Put>();
        Put put1 = new Put(Bytes.toBytes("rowKey1"));
        put1.addColumn(Bytes.toBytes("user"),Bytes.toBytes("name") , Bytes.toBytes("wd"));

        Put put2 = new Put(Bytes.toBytes("rowKey2"));
        put2.addColumn(Bytes.toBytes("user"),Bytes.toBytes("age") , Bytes.toBytes("25"));

        Put put3 = new Put(Bytes.toBytes("rowKey3"));
        put3.addColumn(Bytes.toBytes("user"),Bytes.toBytes("weight") , Bytes.toBytes("60kg"));

        Put put4 = new Put(Bytes.toBytes("rowKey4"));
        put4.addColumn(Bytes.toBytes("user"),Bytes.toBytes("sex") , Bytes.toBytes("男"));
        puts.add(put1);
        puts.add(put2);
        puts.add(put3);
        puts.add(put4);
        table.put(puts);
        table.close();
    }

    /**
     * 添加数据(一个rowKey,一个列簇)
     * @throws IOException
     */
    public void insertSingle() throws IOException {
        Table table = conn.getTable(TableName.valueOf("test"));

        Put put1 = new Put(Bytes.toBytes("rowKey5"));

        put1.addColumn(Bytes.toBytes("user"),Bytes.toBytes("name") , Bytes.toBytes("cm"));
        put1.addColumn(Bytes.toBytes("user"),Bytes.toBytes("age") , Bytes.toBytes("22"));
        put1.addColumn(Bytes.toBytes("user"),Bytes.toBytes("weight") , Bytes.toBytes("88kg"));
        put1.addColumn(Bytes.toBytes("user"),Bytes.toBytes("sex") , Bytes.toBytes("男"));

        table.put(put1);
        table.close();
    }

    /**
     * 根据RowKey,列簇,列名修改值
     * @param tableName
     * @param rowKey
     * @param columnFamily
     * @param columnName
     * @param columnValue
     * @throws IOException
     */
    public static void updateData(TableName tableName,String rowKey,String columnFamily,String columnName,String columnValue) throws IOException {
        Table table = conn.getTable(tableName);
        Put put1 = new Put(Bytes.toBytes(rowKey));
        put1.addColumn(Bytes.toBytes(columnFamily),Bytes.toBytes(columnName) , Bytes.toBytes(columnValue));
        table.put(put1);
        table.close();
    }

    /**
     * 根据rowKey删除一行数据
     * @param tableName
     * @param rowKey
     * @throws IOException
     */
    public static void deleteData(TableName tableName,String rowKey) throws IOException {
        Table table = conn.getTable(tableName);
        Delete delete = new Delete(Bytes.toBytes(rowKey));
        table.delete(delete);
        table.close();
    }

    /**
     * 删除某一行的某一个列簇内容
     * @param tableName
     * @param rowKey
     * @param columnFamily
     * @throws IOException
     */
    public static void deleteData(TableName tableName,String rowKey,String columnFamily) throws IOException {
        Table table = conn.getTable(tableName);
        Delete delete = new Delete(Bytes.toBytes(rowKey));
        delete.addFamily(Bytes.toBytes(columnFamily));
        table.delete(delete);
        table.close();
    }

    /**
     * 删除某一行某个列簇某列的值
     * @param tableName
     * @param rowKey
     * @param columnFamily
     * @param columnName
     * @throws IOException
     */
    public static void deleteData(TableName tableName,String rowKey,String columnFamily,String columnName) throws IOException {
        Table table = conn.getTable(tableName);
        Delete delete = new Delete(Bytes.toBytes(rowKey));
        delete.addColumn(Bytes.toBytes(columnFamily), Bytes.toBytes(columnName));
        table.delete(delete);
        table.close();
    }

    /**
     * 删除某一行某个列簇多个列的值
     * @param tableName
     * @param rowKey
     * @param columnFamily
     * @param columnNames
     * @throws IOException
     */
    public static void deleteData(TableName tableName,String rowKey,String columnFamily,List<String> columnNames) throws IOException {
        Table table = conn.getTable(tableName);
        Delete delete = new Delete(Bytes.toBytes(rowKey));
        for(String columnName:columnNames){
            delete.addColumns(Bytes.toBytes(columnFamily), Bytes.toBytes(columnName));
        }
        table.delete(delete);
        table.close();
    }
    /**
     *根据rowKey查询数据
     * @throws IOException
     */
    public static void getResult(TableName tableName, String rowKey) throws IOException {
        Table table = conn.getTable(tableName);
        //获得一行
        Get get = new Get(Bytes.toBytes(rowKey));
        Result set = table.get(get);
        Cell[] cells  = set.rawCells();
        for(Cell cell : cells) {
            System.out.println(Bytes.toString(cell.getQualifierArray(), cell.getQualifierOffset(), cell.getQualifierLength())+"::"+
                    Bytes.toString(cell.getValueArray(), cell.getValueOffset(), cell.getValueLength()));
        }
        table.close();
    }

    /**
     * 全表扫描
     * @param tableName
     * @throws IOException
     */
    public static  void scanTable(TableName tableName) throws IOException {
        Table table = conn.getTable(tableName);
        Scan scan = new Scan();
        ResultScanner rsacn = table.getScanner(scan);
        for(Result rs:rsacn) {
            String rowkey = Bytes.toString(rs.getRow());
            System.out.println("row key :"+rowkey);
            Cell[] cells  = rs.rawCells();
            for(Cell cell : cells) {
                System.out.println(Bytes.toString(cell.getFamilyArray(),cell.getFamilyOffset(),cell.getFamilyLength())+"::"+Bytes.toString(cell.getQualifierArray(), cell.getQualifierOffset(), cell.getQualifierLength())+"::"+
                        Bytes.toString(cell.getValueArray(), cell.getValueOffset(), cell.getValueLength()));
            }
            System.out.println("-----------------------------------------");
        }
    }


    //过滤器 LESS <  LESS_OR_EQUAL <=  EQUAL =   NOT_EQUAL <>  GREATER_OR_EQUAL >=   GREATER >   NO_OP 排除所有

    /**
     * rowKey过滤器
     * @param tableName
     * @throws IOException
     */
    public static  void rowkeyFilter(TableName tableName) throws IOException {
        Table table = conn.getTable(tableName);
        Scan scan = new Scan();
        RowFilter filter = new RowFilter(CompareOperator.EQUAL,new RegexStringComparator("Key1$"));//str$ 末尾匹配,相当于sql中的 %str  ^str开头匹配,相当于sql中的str%
        scan.setFilter(filter);
        ResultScanner scanner  = table.getScanner(scan);
        for(Result rs:scanner) {
            String rowkey = Bytes.toString(rs.getRow());
            System.out.println("row key :"+rowkey);
            Cell[] cells  = rs.rawCells();
            for(Cell cell : cells) {
                System.out.println(Bytes.toString(cell.getFamilyArray(),cell.getFamilyOffset(),cell.getFamilyLength())+"::"+Bytes.toString(cell.getQualifierArray(), cell.getQualifierOffset(), cell.getQualifierLength())+"::"+
                        Bytes.toString(cell.getValueArray(), cell.getValueOffset(), cell.getValueLength()));
            }
            System.out.println("-----------------------------------------");
        }
    }

    /**
     * 列值过滤器
     * @throws IOException
     */
    public static void singColumnFilter(TableName tableName) throws IOException {
        Table table = conn.getTable(tableName);
        Scan scan = new Scan();
        //下列参数分别为,列族,列名,比较符号,值
        SingleColumnValueFilter filter =  new SingleColumnValueFilter( Bytes.toBytes("author"),  Bytes.toBytes("name"),
                CompareOperator.EQUAL,  Bytes.toBytes("spark")) ;
        scan.setFilter(filter);
        ResultScanner scanner = table.getScanner(scan);
        for(Result rs:scanner) {
            String rowkey = Bytes.toString(rs.getRow());
            System.out.println("row key :"+rowkey);
            Cell[] cells  = rs.rawCells();
            for(Cell cell : cells) {
                System.out.println(Bytes.toString(cell.getFamilyArray(),cell.getFamilyOffset(),cell.getFamilyLength())+"::"+Bytes.toString(cell.getQualifierArray(), cell.getQualifierOffset(), cell.getQualifierLength())+"::"+
                        Bytes.toString(cell.getValueArray(), cell.getValueOffset(), cell.getValueLength()));
            }
            System.out.println("-----------------------------------------");
        }
    }

    /**
     * 列名前缀过滤器
     * @throws IOException
     */
    public static void columnPrefixFilter(TableName tableName) throws IOException {
        Table table = conn.getTable(tableName);
        Scan scan = new Scan();
        ColumnPrefixFilter filter = new ColumnPrefixFilter(Bytes.toBytes("name"));
        scan.setFilter(filter);
        ResultScanner scanner  = table.getScanner(scan);
        for(Result rs:scanner) {
            String rowkey = Bytes.toString(rs.getRow());
            System.out.println("row key :"+rowkey);
            Cell[] cells  = rs.rawCells();
            for(Cell cell : cells) {
                System.out.println(Bytes.toString(cell.getFamilyArray(),cell.getFamilyOffset(),cell.getFamilyLength())+"::"+Bytes.toString(cell.getQualifierArray(), cell.getQualifierOffset(), cell.getQualifierLength())+"::"+
                        Bytes.toString(cell.getValueArray(), cell.getValueOffset(), cell.getValueLength()));
            }
            System.out.println("-----------------------------------------");
        }
    }

    /**
     * 过滤器集合
     * @throws IOException
     */
    public static void filterSet(TableName tableName) throws IOException {
        Table table = conn.getTable(tableName);
        Scan scan = new Scan();
        FilterList list = new FilterList(FilterList.Operator.MUST_PASS_ALL);
        SingleColumnValueFilter filter1 =  new SingleColumnValueFilter( Bytes.toBytes("author"),  Bytes.toBytes("name"),
                CompareOperator.EQUAL,  Bytes.toBytes("spark")) ;
        ColumnPrefixFilter filter2 = new ColumnPrefixFilter(Bytes.toBytes("name"));
        list.addFilter(filter1);
        list.addFilter(filter2);

        scan.setFilter(list);
        ResultScanner scanner  = table.getScanner(scan);
        for(Result rs:scanner) {
            String rowkey = Bytes.toString(rs.getRow());
            System.out.println("row key :"+rowkey);
            Cell[] cells  = rs.rawCells();
            for(Cell cell : cells) {
                System.out.println(Bytes.toString(cell.getFamilyArray(),cell.getFamilyOffset(),cell.getFamilyLength())+"::"+Bytes.toString(cell.getQualifierArray(), cell.getQualifierOffset(), cell.getQualifierLength())+"::"+
                        Bytes.toString(cell.getValueArray(), cell.getValueOffset(), cell.getValueLength()));
            }
            System.out.println("-----------------------------------------");
        }

    }
}
  • 4
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 9
    评论
### 回答1: HBase是一个分布式的、面向列的NoSQL数据库,它是建立在Hadoop之上的。HBase提供了Java API来管理表,这些API可以用来创建、删除、修改和查询表。使用Java API可以方便地与HBase进行交互,实现数据的读写和管理。在使用Java API时,需要先创建一个HBaseConfiguration对象,然后通过该对象创建一个HBaseAdmin对象,通过HBaseAdmin对象可以进行表的管理操作。同时,还可以使用HBase的Put和Get对象来进行数据的读写操作。总之,使用Java API可以方便地管理HBase表,实现数据的高效存储和查询。 ### 回答2: HBase是一个高可扩展性、高可靠性的分布式列存储系统,常用于海量数据的存储与实时查询。在HBase中,表被分成若干区域(Region),每个Region包含一段rowkey范围内的数据。HBase使用Zookeeper协调Region Server和HMaster的进程启动和监管系统,其提供了简单的Java API进行操作和使用。 HBase中的Java API提供了一系列操作表的方法,主要包括创建表、删除表、获取表信息、插入数据、查询数据和删除数据等操作。 首先,创建表需要确定表名、列族和行键的设计。使用Java API时,可使用TableDescriptorBuilder来创建表的描述,其中需要指定表名和列族名。对于每个列族,需要指定数据是否压缩、存储类型等信息。 其次,对于已有表进行删除时,首先要停止对该表的所有操作,并将其进行禁用。使用Java API时,可使用Admin.disableTable()方法对表进行禁用,然后通过Admin.deleteTable()方法将表进行删除。 获取表信息可使用Admin.getDescriptor()方法获取表的描述信息,包括表名、列族和数据存储信息等。 对于插入数据,HBase中的数据是以KV(Key-Value)的形式存储,所以需要一个Put对象来承载需要存储的数据。使用Table.put()方法可以将数据存储到对应的表中。 查询数据可使用Scan或Get方法,其中Scan可针对整个表进行扫描,Get可获取指定的行键的数据。使用Scan和Get方法可获取批量数据和单条数据,具体使用时根据实际情况进行选择。 删除数据可使用Delete方法,可以删除指定行键的数据。使用Table.delete()方法可以实现对数据的删除操作。 总之,HBaseJava API提供了方便快捷的方式对HBase的表进行管理和操作,可以很好地满足海量数据的存储和实时查询需求。 ### 回答3: HBase是一个开源的NoSQL数据库,采用分布式存储的方式来存储数据,并且可以在百万级别的数据规模下保证数据的高可靠性、高可扩展性和高性能。HBase提供了Java API来管理表,实现数据的增删改查等操作。 在使用HBase Java API管理表时,需要先连接到HBase集群。可以通过HBaseConfiguration类来创建一个Configuration实例,该实例包含了与Hadoop和HBase相关的配置信息,然后通过ConnectionFactory类的createConnection方法来创建一个Connection实例,即可连接到HBase集群。 对于表的管理,HBase提供了Table类,通过该类的实例可以进行数据的增删改查操作。需要通过TableDescriptorBuilder构建表的描述信息,包括表名、列族等信息,然后通过Admin类的createTable方法来创建表。如果需要删除表,则可以使用Admin类的deleteTable方法来删除表。 对于数据的增删改查操作,需要先获取到Table类的实例,然后通过Put类、Delete类和Get类来进行数据的插入、删除和查询操作。对于Put类的实例,需要通过addColumn方法来定义要插入的列族和列,然后通过add方法来设置列的值;对于Delete类的实例,需要通过addColumn方法来定义要删除的列族和列;对于Get类的实例,则需要通过addColumn方法来定义要查询的列族和列,然后通过Result类的实例来获取查询结果。 在进行数据操作时,如果需要批量操作,可以使用Batch类的实例来进行批量操作。Batch类提供了一系列add方法用于添加Put、Delete和Increment对象,然后通过Table类的batch方法来批量提交操作。 总之,HBase Java API提供了一系列方便的方法来管理表和进行数据操作,可以满足大规模数据存储的需求。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

泪痕残

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值