0

0

hbase Java API操作实例

php中文网

php中文网

发布时间:2016-06-07 16:41:19

|

2146人浏览过

|

来源于php中文网

原创

DDL(创建及删除表格) 如何在hbase中创建表格以及删除表格。可通过java和hbase shell两种方法实现。 创建表格 HBase中表格的创建是通过对操作HBaseAdmin这一对象使其调用createTable()这一方法来实现。 其中HTableDescriptor描述了表的schema,可在其上通过

DDL(创建及删除表格)

如何在hbase中创建表格以及删除表格。可通过java和hbase shell两种方法实现。

创建表格

HBase中表格的创建是通过对操作HBaseAdmin这一对象使其调用createTable()这一方法来实现。

其中HTableDescriptor描述了表的schema,可在其上通过addFamily()这一方法增加列族。

以下Java代码实现了建立一张简易的Hbase表格‘table1’,该表有两个列族,分别为f1和f2。

public class createTable{
    private static Configuration config;
    private static HBaseAdmin ha;
    public static void main(String[] args){ 
        try{
            config = HBaseConfiguration.create();
            config.addResource("core-site.xml");
            config.addResource("hdfs-site.xml");
            config.addResource("yarn-site.xml");
            config.addResource("mapred-site.xml");
            ha = new HBaseAdmin(config);
            //create table descriptor
            String tableName = "table1";
            HTableDescriptor htd = new HTableDescriptor(Bytes.toBytes(tableName));
            //create and configure column families
            HColumnDescriptor hcd1 = new HColumnDescriptor(Bytes.toBytes("family1"));
            hcd1.setBlocksize(65536);  
            hcd1.setMaxVersions(1); 
            hcd1.setBloomFilterType(BloomType.ROW); 
            hcd1.setCompressionType(Algorithm.SNAPPY);          
            hcd1.setDataBlockEncoding(DataBlockEncoding.PREFIX); 
            hcd1.setTimeToLive(36000);
            hcd1.setInMemory(false);
            HColumnDescriptor hcd2 = new HColumnDescriptor(Bytes.toBytes("family2"));
            hcd2.setBlocksize(65536);
            hcd2.setMaxVersions(1); 
            hcd2.setBloomFilterType(BloomType.ROW); 
            hcd2.setCompressionType(Algorithm.SNAPPY);          
            hcd2.setDataBlockEncoding(DataBlockEncoding.PREFIX); 
            hcd2.setTimeToLive(36000);
            hcd2.setInMemory(false);
            //add column families to table descriptor
            htd.addFamily(hcd1);
            htd.addFamily(hcd2);
            //create table
            ha.createTable(htd); 
            System.out.println("Hbase table created.");
        }catch (TableExistsException e){
            System.out.println("ERROR: attempting to create existing table!");
        }catch (IOException e){
            e.printStackTrace();
        }finally{
            try{
                ha.close();
            }catch(IOException e){
                e.printStackTrace();
            }
        }
    }
}

在Hbase Shell中,创建表格功能由create ‘Hbase表名’,[‘列族名’...]来实现。

立即学习Java免费学习笔记(深入)”;

例如,create ‘table1’,‘family1’,‘family2’同样可创建上述表格。

删除表格

删除表也是通过HBaseAdmin来操作,删除表之前首先要disable表。这是一个比较耗时的操作,所以不建议频繁删除表。

以下Java代码实现了对表格“table1”的删除操作:

public class deleteTable{
    private static Configuration config;
    private static HBaseAdmin ha;
    public static void main(String[] args){
        try{
            config = HBaseConfiguration.create(); 
            config.addResource("core-site.xml");
            config.addResource("hdfs-site.xml");
            config.addResource("yarn-site.xml");
            config.addResource("mapred-site.xml");           
            ha = new HBaseAdmin(config);
            String tableName = "table1";
            //Only an existing table can be dropped
            if (ha.tableExists(tableName)){
                //read&write denied
                ha.disableTable(tableName);
                ha.deleteTable(tableName);
                System.out.println("Hbase table dropped!");
            }
        }catch(IOException e){
            e.printStackTrace();
        }finally{
            try{
                ha.close();
            }catch(IOException e){
                e.printStackTrace();
            }
        }
    }
}

在Hbase Shell中,删除表格功能由drop ‘Hbase表名’来实现。

例如,先disable ‘table1’再drop ‘table1’同样可删除上述表格。

数据插入

在Java操作中,put方法被用做插入数据。

put方法可以传递单个Put对象: public void put(Put put) throws IOException,也可以对很多Put对象进行批量插入: public void put(List puts) throws IOException

以下Java代码实现了对表格"table1"的批量数据插入操作。插入数据后,表格有10000行,列族“family1”,“family2”中都包含“q1”,“q2”两个列,其中列族“family1”储存整型数据(int),列族“family2”储存字符串(string)。

台讯电子企业网站管理系统  简繁全功能版
台讯电子企业网站管理系统 简繁全功能版

超级适合代理建设企业站点的企业源码,超方面实用!程序说明: 1.特色:简繁中文切换、产品展示系统、新闻发布系统、会员管理系统、留言本计数器、网站信息统计、强大后台操作 功能等; 2.页面包括:首页、企业介绍、滚动公告通知发布系统、企业新闻系统、产品展示系统、企业案例发布展示系 统、企业招聘信息发布系统、信息资源下载系统、在线定单系统、在线客服系统、在线留言本系统、网站调查投票系统、友情连接系统、会

下载

ATTENTION:虽然Hbase支持多种类型储存,但为了应用高性能优化的hbase,表格值的储存类型建议一致使用为String。如上例所示,“family1:q1”中原为整数类型,须转制成string后再录入表中

public class insertTable{
    private static Configuration config;
    public static void main(String[] args) throws IOException{
        config = HBaseConfiguration.create();
        config.addResource("core-site.xml");
        config.addResource("hdfs-site.xml");
        config.addResource("yarn-site.xml");
        config.addResource("mapred-site.xml");
        String tableName = "table1";
        HTable table = new HTable(config, tableName);
        //set AutoFlush
        table.setAutoFlush(true);
        int count = 10000;
        String familyName1 = "family1";
        String familyName2 = "family2";
        String qualifier1 = "q1";
        String qualifier2 = "q2";
        //data to be inserted
        String[] f1q1 = new String[count];
        String[] f1q2 = new String[count];
        String[] f2q1 = new String[count];
        String[] f2q2 = new String[count];
        for(int i = 0; i < count; i++){
            f1q1[i] = Integer.toString(i);
            f1q2[i] = Integer.toString(i+10000);
            f2q1[i] = String.format("f2q1%d", i);
            f2q2[i] = String.format("f2q2%d", i);           
        }
        List puts = new ArrayList();
        //insert by rows
        for (int j = 0; j < count; j++){
            //Create a Put object for a specified row-key
            Put p = new Put(Bytes.toBytes(String.format("Row%05d",j)));
            //fill columns
            p.add(Bytes.toBytes(familyName1), Bytes.toBytes(qualifier1), Bytes.toBytes(f1q1[j]));
            p.add(Bytes.toBytes(familyName1), Bytes.toBytes(qualifier2), Bytes.toBytes(f1q2[j])); 
            p.add(Bytes.toBytes(familyName2), Bytes.toBytes(qualifier1), Bytes.toBytes(f2q1[j])); 
            p.add(Bytes.toBytes(familyName2), Bytes.toBytes(qualifier2), Bytes.toBytes(f2q2[j]));
            puts.add(p);
            //put for every 100 rows
            if((j+1)%100==0){
                table.put(puts);
                puts.clear(); 
            }
        }
        table.close();
        System.out.println("Data inserted!");
   }
}

在Hbase Shell中,单条数据插入功能由put ‘Hbase表名’,‘rowKey’,‘列族名:列名’,‘数据值’来实现。

数据查询

Hbase表格的数据查询可分为单条查询与批量查询。

单条查询

单条查询是通过匹配rowkey在表格中查询某一行的数据。在Java中可通过get()这一方法来实现。
下列Java代码实现了在表格“table1”中取出指定rowkey一行的所有列的数据:

public class getFromTable{
    private static Configuration config;
    public static void main(String[] args) throws IOException{
        String tableName = "table1";
        config = HBaseConfiguration.create();
        config.addResource("core-site.xml");
        config.addResource("hdfs-site.xml");
        config.addResource("yarn-site.xml");
        config.addResource("mapred-site.xml"); 
        HTable table = new HTable(config, tableName);
        Get get = new Get(Bytes.toBytes("Row01230"));
        //add target columns for get
        get.addColumn(Bytes.toBytes("family1"), Bytes.toBytes("q1"));
        get.addColumn(Bytes.toBytes("family1"), Bytes.toBytes("q2")); 
        get.addColumn(Bytes.toBytes("family2"), Bytes.toBytes("q1"));
        get.addColumn(Bytes.toBytes("family2"), Bytes.toBytes("q2")); 
        Result result =  table.get(get);
        //get results
        byte[] rowKey = result.getRow();
        byte[] val1 = result.getValue(Bytes.toBytes("family1"), Bytes.toBytes("q1"));            
        byte[] val2 = result.getValue(Bytes.toBytes("family1"),Bytes.toBytes("q2"));
        byte[] val3 = result.getValue(Bytes.toBytes("family2"), Bytes.toBytes("q1"));
        byte[] val4 = result.getValue(Bytes.toBytes("family2"), Bytes.toBytes("q2")); 
        System.out.println("Row key: " + Bytes.toString(rowKey));
        System.out.println("value1: " + Bytes.toString(val1));               
        System.out.println("value2: " + Bytes.toString(val2)); 
        System.out.println("value3: " + Bytes.toString(val3));               
        System.out.println("value4: " + Bytes.toString(val4));
        table.close();
    }
}

在Hbase Shell中,单条数据查找功能由get ‘Hbase表名’,‘rowKey’,‘列族名:列名’来实现。

批量查询

批量查询是通过制定一段rowkey的范围来查询。可通过Java中getScanner()这一方法来实现。
下列Java代码实现了在表格“table1”中取出指定一段rowkey范围的所有列的数据:

public class scanFromTable {
    private static Configuration config;
    public static void main(String[] args) throws IOException{
        config = HBaseConfiguration.create();
        config.addResource("core-site.xml");
        config.addResource("hdfs-site.xml");
        config.addResource("yarn-site.xml");
        config.addResource("mapred-site.xml");
        String tableName = "table1";
        HTable table = new HTable(config, tableName);
        //Scan according to rowkey range
        Scan scan = new Scan();
        //set starting row(included), if not set, start from the first row
        scan.setStartRow(Bytes.toBytes("Row01000"));
        //set stopping row(excluded), if not set, stop at the last row 
        scan.setStopRow(Bytes.toBytes("Row01100"));
        //specify columns to scan, if not specified, return all columns; 
        scan.addColumn(Bytes.toBytes("family1"), Bytes.toBytes("q1"));
        scan.addColumn(Bytes.toBytes("family1"), Bytes.toBytes("q2"));
        scan.addColumn(Bytes.toBytes("family2"), Bytes.toBytes("q1"));
        scan.addColumn(Bytes.toBytes("family2"), Bytes.toBytes("q2"));
        //specify maximum versions for one cell, if called without arguments, get all versions, if not called, get only the latest version
        scan.setMaxVersions();
        //specify maximum number of cells to avoid OutOfMemory error caused by huge amount of data in a single row
        scan.setBatch(10000);
        ResultScanner rs = table.getScanner(scan);
        for(Result r:rs){
            byte[] rowKey = r.getRow();
            byte[] val1 = r.getValue(Bytes.toBytes("family1"), Bytes.toBytes("q1"));
            byte[] val2 = r.getValue(Bytes.toBytes("family1"), Bytes.toBytes("q2"));
            byte[] val3 = r.getValue(Bytes.toBytes("family2"), Bytes.toBytes("q1"));
            byte[] val4 = r.getValue(Bytes.toBytes("family2"), Bytes.toBytes("q2"));
            System.out.print(Bytes.toString(rowKey)+": ");
            System.out.print(Bytes.toString(val1)+" ");
            System.out.print(Bytes.toString(val2)+" ");
            System.out.print(Bytes.toString(val3)+" ");
            System.out.println(Bytes.toString(val4));
        }
        rs.close();
        table.close();
    }
}   

在Hbase Shell中,批量数据查找功能由scan ‘Hbase表名’,{COLUMNS=>‘列族名:列名’,STARTROW=>‘起始rowkey’,STOPROW=>‘终止rowkey’}来实现。

利用过滤器筛选

过滤器是在Hbase服务器端上执行筛选操作,可以应用到行键(RowFilter),列限定符(QualifierFilter)以及数据值(ValueFilter)。

这里列举了两个常用的过滤器:RowFilter和SingleColumnValueFilter。

RowFilter

RowFilter通过行键(rowkey)来筛选数据。

其中BinaryComparator直接比较两个byte array,可选的比较符(CompareOp)有EQUAL,NOT_EQUAL,GREATER,GREATER_OR_EQUAL,LESS,LESS_OR_EQUAL。

public class rowFilter{
    public static void main(String[] args) throws IOException{
        String tableName = "table1";
        Configuration config = HBaseConfiguration.create();
        config.addResource("core-site.xml");
        config.addResource("hdfs-site.xml");
        config.addResource("yarn-site.xml");
        config.addResource("mapred-site.xml");
        HTable table = new HTable(config, tableName);
        Scan scan = new Scan();
        scan.addColumn(Bytes.toBytes("family1"), Bytes.toBytes("q1"));
        Filter filter = new RowFilter(CompareFilter.CompareOp.EQUAL, new BinaryComparator(Bytes.toBytes("Row01234")));
        scan.setFilter(filter);
        ResultScanner scanner = table.getScanner(scan);
        for(Result res:scanner){
            byte[] value = res.getValue(Bytes.toBytes("family1"),Bytes.toBytes("q1"));         
            System.out.println(new String(res.getRow())+" value is: "+Bytes.toString(value));
        }
        scanner.close();
        table.close();    
    }
}

SingleColumnValueFilter

SingleColumnValueFilter对某一具体列的值进行筛选。

其中SubstringComparator检查给定的字符串是否是列值的子字符串,可选的比较符(CompareOp)有EQUAL和NOT_EQUAL。

public class singleColumnValueFilter{
    public static void main(String[] args) throws IOException{
        Configuration config = HBaseConfiguration.create();
        config.addResource("core-site.xml");
        config.addResource("hdfs-site.xml");
        config.addResource("yarn-site.xml");
        config.addResource("mapred-site.xml"); 
        String tableName = "table1";
        HTable table = new HTable(config,tableName);     
        SingleColumnValueFilter filter = new SingleColumnValueFilter(
                Bytes.toBytes("family2"),
                Bytes.toBytes("q1"),
                CompareFilter.CompareOp.NOT_EQUAL,
                new SubstringComparator("45"));
        //when setting setFilterIfMissing(true), rows with "null" values are filtered
        filter.setFilterIfMissing(true);
        Scan scan = new Scan();
        scan.setFilter(filter);
        ResultScanner scanner = table.getScanner(scan);
        for (Result res:scanner){
            byte[] val = res.getValue(Bytes.toBytes("family1"), Bytes.toBytes("q1"));
            System.out.println(new String(res.getRow()));
            System.out.println("value: " + Bytes.toString(val)); 
        }
        scanner.close();
        table.close();
    }
}

相关文章

java速学教程(入门到精通)
java速学教程(入门到精通)

java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载

相关标签:

本站声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热门AI工具

更多
DeepSeek
DeepSeek

幻方量化公司旗下的开源大模型平台

豆包大模型
豆包大模型

字节跳动自主研发的一系列大型语言模型

通义千问
通义千问

阿里巴巴推出的全能AI助手

腾讯元宝
腾讯元宝

腾讯混元平台推出的AI助手

文心一言
文心一言

文心一言是百度开发的AI聊天机器人,通过对话可以生成各种形式的内容。

讯飞写作
讯飞写作

基于讯飞星火大模型的AI写作工具,可以快速生成新闻稿件、品宣文案、工作总结、心得体会等各种文文稿

即梦AI
即梦AI

一站式AI创作平台,免费AI图片和视频生成。

ChatGPT
ChatGPT

最最强大的AI聊天机器人程序,ChatGPT不单是聊天机器人,还能进行撰写邮件、视频脚本、文案、翻译、代码等任务。

相关专题

更多
俄罗斯Yandex引擎入口
俄罗斯Yandex引擎入口

2026年俄罗斯Yandex搜索引擎最新入口汇总,涵盖免登录、多语言支持、无广告视频播放及本地化服务等核心功能。阅读专题下面的文章了解更多详细内容。

178

2026.01.28

包子漫画在线官方入口大全
包子漫画在线官方入口大全

本合集汇总了包子漫画2026最新官方在线观看入口,涵盖备用域名、正版无广告链接及多端适配地址,助你畅享12700+高清漫画资源。阅读专题下面的文章了解更多详细内容。

35

2026.01.28

ao3中文版官网地址大全
ao3中文版官网地址大全

AO3最新中文版官网入口合集,汇总2026年主站及国内优化镜像链接,支持简体中文界面、无广告阅读与多设备同步。阅读专题下面的文章了解更多详细内容。

79

2026.01.28

php怎么写接口教程
php怎么写接口教程

本合集涵盖PHP接口开发基础、RESTful API设计、数据交互与安全处理等实用教程,助你快速掌握PHP接口编写技巧。阅读专题下面的文章了解更多详细内容。

2

2026.01.28

php中文乱码如何解决
php中文乱码如何解决

本文整理了php中文乱码如何解决及解决方法,阅读节专题下面的文章了解更多详细内容。

4

2026.01.28

Java 消息队列与异步架构实战
Java 消息队列与异步架构实战

本专题系统讲解 Java 在消息队列与异步系统架构中的核心应用,涵盖消息队列基本原理、Kafka 与 RabbitMQ 的使用场景对比、生产者与消费者模型、消息可靠性与顺序性保障、重复消费与幂等处理,以及在高并发系统中的异步解耦设计。通过实战案例,帮助学习者掌握 使用 Java 构建高吞吐、高可靠异步消息系统的完整思路。

8

2026.01.28

Python 自然语言处理(NLP)基础与实战
Python 自然语言处理(NLP)基础与实战

本专题系统讲解 Python 在自然语言处理(NLP)领域的基础方法与实战应用,涵盖文本预处理(分词、去停用词)、词性标注、命名实体识别、关键词提取、情感分析,以及常用 NLP 库(NLTK、spaCy)的核心用法。通过真实文本案例,帮助学习者掌握 使用 Python 进行文本分析与语言数据处理的完整流程,适用于内容分析、舆情监测与智能文本应用场景。

24

2026.01.27

拼多多赚钱的5种方法 拼多多赚钱的5种方法
拼多多赚钱的5种方法 拼多多赚钱的5种方法

在拼多多上赚钱主要可以通过无货源模式一件代发、精细化运营特色店铺、参与官方高流量活动、利用拼团机制社交裂变,以及成为多多进宝推广员这5种方法实现。核心策略在于通过低成本、高效率的供应链管理与营销,利用平台社交电商红利实现盈利。

122

2026.01.26

edge浏览器怎样设置主页 edge浏览器自定义设置教程
edge浏览器怎样设置主页 edge浏览器自定义设置教程

在Edge浏览器中设置主页,请依次点击右上角“...”图标 > 设置 > 开始、主页和新建标签页。在“Microsoft Edge 启动时”选择“打开以下页面”,点击“添加新页面”并输入网址。若要使用主页按钮,需在“外观”设置中开启“显示主页按钮”并设定网址。

72

2026.01.26

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
Kotlin 教程
Kotlin 教程

共23课时 | 3万人学习

C# 教程
C# 教程

共94课时 | 7.9万人学习

Java 教程
Java 教程

共578课时 | 52.7万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号