hbase java sample
admin
2023-02-08 11:00:07
0
  1. 通过HBaseAdmin维护表(创建,删除表)

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.client.HBaseAdmin;
public class CreateHbaseTable {
    public static void main(String[] args) throws Exception {
       String tbl = "ericni_test";
        Configuration config = HBaseConfiguration. create();
        config.set( "hbase.zookeeper.quorum", "xxxx" );
        config.set( "hbase.zookeeper.property.clientPort" , "2181" );
        HBaseAdmin admin = new HBaseAdmin(config);
        HTableDescriptor[] tables = admin.listTables();
        for(HTableDescriptor t:tables){
            System. out.println(t.getNameAsString());
        }
        if (admin.tableExists(tbl.getBytes("utf8" ))) {
           System. out.println("table already exists!" );
        } else {
            System. out.println("table not already exists!create now!" );
            creatTable(admin,tbl,new String[]{ "info"});
       }
    }
    public static void creatTable(HBaseAdmin admin,String tableName, String[] familys) throws Exception {
            HTableDescriptor tableDesc = new HTableDescriptor(tableName);
            for(int i=0; i

2.通过Put写入数据

import java.io.File;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.client.HBaseAdmin;
import org.apache.hadoop.hbase.client.HTable;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.util.Bytes;
public class LoadDataFromFile {
    public static void main(String[] args) throws Exception {
       String tbl = "ericni_test";
       String filename = "/tmp/click.log";
       File file = new File(filename);  
       BufferedReader reader = null;
        reader = new BufferedReader(new FileReader(file));
        Configuration config = HBaseConfiguration. create();
        config.set( "hbase.zookeeper.quorum", "10.100.90.203" );
        config.set( "hbase.zookeeper.property.clientPort" , "2181" );
        HTable table = new HTable(config, tbl);
        HBaseAdmin admin = new HBaseAdmin(config);
        if (admin.tableExists(tbl.getBytes("utf8" ))) {
           System. out.println("table already exists!" );
           try {
               try {
                   String tmpString = null;
                   int linex = 1;
                   while ((tmpString = reader.readLine()) != null) {
                           //System.out.println(tmpString.getClass());
                           String[] lines = tmpString.split( "\\t");
                           //String[] newlines = {lines[0],lines[1],lines[2],lines[3],lines[4]};  
                           //String row = StringUtils.join(new String[] {lines[0],lines[1],lines[2],lines[3],lines[4]}, "_");
                           StringBuffer sb = new StringBuffer();
                           String row = sb.append(lines[0]).append("_" ).append(lines[1]).append("_").append(lines[2]).append( "_").append(lines[3]).append("_" ).append(lines[4]).toString();
                           String valuex = lines[lines. length-1];                      
                           System. out.println(row);
                           linex ++;
                              addRecord(table,tbl,row, "Stat", "Click_cnt", valuex);
                   }
                   reader.close();
           } catch(IOException err){
                   err.printStackTrace();
           } finally {
                   try{
                           if(reader != null) reader.close();
                   } catch(IOException err){
                           err.printStackTrace();
                   }
           }
              
           } catch(Exception err){
                 System. out.println("load data error" );
                 System. out.println("error log: " + err);
                 err.printStackTrace();
           }        
          
        } else {
            System. out.println("table not already exists!" );
            System. exit(1);
       }
        table.close();
        admin.close();
    }
     public static void addRecord(HTable table,String tableName, String rowKey, String family, String qualifier, String value) throws Exception{
            Put put = new Put(Bytes.toBytes(rowKey));
            put.add(Bytes. toBytes(family), Bytes.toBytes(qualifier), Bytes.toBytes(value));
            table.put(put);
            System. out.println("insert recored " + rowKey + " to table " + tableName + " ok." );
        }
   
}

3.Scan的Filter操作

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;      
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.KeyValue;
import org.apache.hadoop.hbase.client.Get;
import org.apache.hadoop.hbase.client.HTable;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.ResultScanner;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.filter.FilterList;
import org.apache.hadoop.hbase.filter.SingleColumnValueFilter;
import org.apache.hadoop.hbase.filter.CompareFilter.CompareOp;
import org.apache.hadoop.hbase.util.Bytes;
public class FilterTest {
    private static Configuration config = null;
    private static HTable table;
    private static HTable table2;
    private static HTable table3;
    static {
        try {
            config = HBaseConfiguration.create();
            config.set("hbase.zookeeper.quorum" , "xxxxx" );    
            config.set("hbase.zookeeper.property.clientPort" , "2181" );
        } catch (Exception e){
            e.printStackTrace();
        }
    }
    public static void selectByRowKey(String tablename,String rowKey) throws IOException{
        table = new HTable(config,tablename);
        Get g = new Get(Bytes.toBytes(rowKey));
        Result r = table.get(g);
        for(KeyValue kv:r.raw()){
            System. out.println("row : " +new String(kv.getRow()));
            System. out.println("column: " +new String(kv.getKey()));
            System. out.println("value: " +new String(kv.getValue()));
        }
    }   
    public static void selectByRowKeyColumn(String tablename,String rowKey,String column,String qualifier) throws IOException{
        table2 = new HTable(config,tablename);
        Get g = new Get(Bytes.toBytes(rowKey));
        g.addColumn(Bytes. toBytes(column),qualifier.getBytes("utf8"));
        Result r = table2.get(g);
        for(KeyValue kv:r.raw()){
            System. out.println("row : " +new String(kv.getRow()));
            System. out.println("column: " +new String(kv.getKey()));
            System. out.println("value: " +new String(kv.getValue()));
        }
    } 
    public static void selectByFilter(String tablename,List arr) throws IOException{
        table3 = new HTable(config,tablename);
        FilterList filterList = new FilterList();
        Scan s1 = new Scan();
        for(String v:arr){
            String[] s = v.split( ",");
            filterList.addFilter( new SingleColumnValueFilter(Bytes.toBytes(s[0]),
                                                             Bytes.toBytes(s[1]),
                                                             CompareOp.EQUAL,Bytes.toBytes(s[2])
                                                             )
            );
            s1.addColumn(Bytes. toBytes(s[0]), Bytes.toBytes(s[1]));
        }
        s1.setFilter(filterList);
        ResultScanner ResultScannerFilterList = table3.getScanner(s1);
        for(Result rr = ResultScannerFilterList.next();rr != null;rr = ResultScannerFilterList.next()){
            for(KeyValue kv:rr.list()){
                System. out.println("row : " +new String(kv.getRow()));
                System. out.println("column : " +new String(kv.getKey()));
                System. out.println("value : " +new String(kv.getValue()));
            }
        }
    }    
    public static void main(String[] args) throws IOException{          
       //selectByRowKey("ericni_test","102_2.94_1400342400_00426_01132");              
           //selectByRowKeyColumn("ericni_test","102_2.94_1400342400_00426_01132"," Stat","Click_cnt");             
        List arr= new ArrayList();
        arr.add( "Stat,Click_cnt,1");
        selectByFilter("ericni_test" ,arr);
    }    
}


相关内容

热门资讯

专访王虹:从北大数学系曾经的“... “获奖挺好的。”王虹说话慢慢的,随后话锋一转,带着自嘲式的笑意,“但是题该做不出来,还是做不出来。”...
意大利纵火犯用猫助燃,当地动保... 【环球时报记者 林泽宇 环球时报特约记者 文简】据《意大利晨报》23日报道,近日意大利南部野火肆虐。...
第8国?美媒爆料:美政府正研究... 【环球时报综合报道】据美国《华盛顿邮报》23日报道,多名美国官员透露,美政府正研究是否在西非国家马里...
男子在采血站采血后口吐白沫、神... 7月23日,山西广播电视台《慧帮忙》栏目报道“我弟弟在霍州康宝生物科技采血站采血后口吐白沫、神志不清...
“安全先生”,不安全了 当地时间7月17日凌晨,以色列第25届议会以62票赞成、0票反对通过一项有关政党经费法的相关修正案,...
“AI科学家”,实验效率直接“... □ 本报记者 洪叶 徐春晖 窗明几净的空间里没有科研人员,取而代之的是一排充满科技感的自动化岛台,背...
云南一女子电脑屏内现“蚂蚁窝”... 大家平时清洁电脑显示屏吗? 你见过显示屏里进蚂蚁吗? 据媒体报道,云南临沧一名女子近期发现,自己使...
便携脑电采集新品发布,脑电信号... 一根发带将一个比硬币略大的采集设备贴在额头,就能实现脑电信号采集,脑机接口创新企业神舞科技7月22日...
工业和信息化部:依托标准牵引智... 日前,在北京举办的《人工智能 智能体互联》系列标准应用推进专题会上,工业和信息化部科技司副司长甘小斌...