SlideShare a Scribd company logo
HBase Programming

        Mani
 mmaniga@yahoo.co.uk
CreateTable
public static int VERSION = 5;

public static void createTable(byte[] tableName,
          byte[][] families,
          int numVersions) throws IOException {

HBaseConfiguration hbaseConfig = new HBaseConfiguration();
HBaseAdmin hbaseAdmin = new HBaseAdmin(hbaseConfig);
HTableDescriptor htableDesc = new HTableDescriptor(tableName);
     for (byte[] family : families) {
          HColumnDescriptor hColumnDescriptor = new HColumnDescriptor(family,
                    numVersions, HColumnDescriptor.DEFAULT_COMPRESSION,
                    HColumnDescriptor.DEFAULT_IN_MEMORY,
                    HColumnDescriptor.DEFAULT_BLOCKCACHE,
                    HColumnDescriptor.DEFAULT_TTL,
                    HColumnDescriptor.DEFAULT_BLOOMFILTER);
          htableDesc.addFamily(hColumnDescriptor);
          }
          hbaseAdmin.createTable(htableDesc);

    }
Table Exists & Get Table Name
public static boolean tableExist(byte[] tableName) throws IOException {
          HBaseConfiguration hbaseConfig = new HBaseConfiguration();
          HBaseAdmin hbaseAdmin = new HBaseAdmin(hbaseConfig);
          return hbaseAdmin.tableExists(tableName);
     }
public static List<String> getTableNames() throws IOException {
          HBaseConfiguration hbaseConfig = new HBaseConfiguration();
          HBaseAdmin hbaseAdmin = new HBaseAdmin(hbaseConfig);

         List<String> tables = new ArrayList<String>();
         for (HTableDescriptor htableDesc : hbaseAdmin.listTables()) {
              printTableDescriptors(htableDesc);
              tables.add(htableDesc.getNameAsString());
         }
         return tables;
     }
public static void printTableDescriptors(HTableDescriptor descriptor) {
          System.out.println("Table name " + descriptor.getNameAsString());
          for (HColumnDescriptor columnDescriptor : descriptor.getColumnFamilies()) {
               System.out.println(columnDescriptor.getNameAsString());
               System.out.println(columnDescriptor.getMaxVersions());
               System.out.println(columnDescriptor.getMinVersions());
          }
     }
Insert Record
public static void insertRecord(HTable htable, byte[] columnFamily,
          boolean createColumnFamily,
          HashMap<String, HashMap<String, String>> creditLogMaps) throws IOException {
          String rowKey;// record key
          HashMap<String, String> columnData;
          if (!columnFamilyExist(htable, columnFamily)) {
               if (!createColumnFamily)
                    return;
               else
                    createColumnFamily(htable, columnFamily, VERSION);
          }
          for (Map.Entry<String, HashMap<String, String>> creditLogMap :
creditLogMaps.entrySet()) {
               rowKey = creditLogMap.getKey();
               columnData = creditLogMap.getValue();
               Put put = new Put(rowKey.getBytes());
               for (Map.Entry<String, String> kv : columnData.entrySet()) {
                    put.add(columnFamily, kv.getKey().getBytes(), kv.getValue()
                    .getBytes());
               }
               htable.put(put);
               System.out.println("Record inserted");
          }
     }
Create Column Family
public static void createColumnFamily(HTable htable,
               byte[] columnFamily,
               int numVersions) throws IOException {

           disableTable(htable.getTableName());

           while (isTableEnabled(htable.getTableName()));// wait untill table is
disabled

           HBaseConfiguration hbaseConfig = new HBaseConfiguration();
           HBaseAdmin hbaseAdmin = new HBaseAdmin(hbaseConfig);

           HColumnDescriptor hColumnDescriptor = new HColumnDescriptor(
                     columnFamily, numVersions,
                     HColumnDescriptor.DEFAULT_COMPRESSION,
                     HColumnDescriptor.DEFAULT_IN_MEMORY,
                     HColumnDescriptor.DEFAULT_BLOCKCACHE,
                     HColumnDescriptor.DEFAULT_TTL,
                     HColumnDescriptor.DEFAULT_BLOOMFILTER);

           hbaseAdmin.addColumn(htable.getTableName(), hColumnDescriptor);

           enableTable(htable.getTableName());
    }
Get Column Family
public static List<String> getColumnFamilies(HTable htable) throws IOException {
          List<String> columnFamilies = new ArrayList<String>();
          for (HColumnDescriptor columnDesc :
htable.getTableDescriptor().getColumnFamilies()) {
               columnFamilies.add(columnDesc.getNameAsString());
          }
          return columnFamilies;
     }

public static boolean columnFamilyExist(HTable htable, byte[] columnFamily)
throws IOException {
          boolean hasColumn = false;
          if (htable.getTableDescriptor().getFamily(columnFamily) != null) {
               hasColumn = true;
          }
          return hasColumn;
     }

public static boolean isTableEnabled(byte[] tableName) throws IOException {
          HBaseConfiguration hbaseConfig = new HBaseConfiguration();
          HBaseAdmin hbaseAdmin = new HBaseAdmin(hbaseConfig);
          System.out.println("Table enabled " + hbaseAdmin.isTableEnabled(tableName));
          return hbaseAdmin.isTableEnabled(tableName);
     }
Enable, Disable & Drop Table
public static void enableTable(byte[] tableName) throws IOException {
          HBaseConfiguration hbaseConfig = new HBaseConfiguration();
          HBaseAdmin hbaseAdmin = new HBaseAdmin(hbaseConfig);
          hbaseAdmin.enableTable(tableName);
     }

    public static void disableTable(byte[] tableName) throws IOException {
         HBaseConfiguration hbaseConfig = new HBaseConfiguration();
         HBaseAdmin hbaseAdmin = new HBaseAdmin(hbaseConfig);
         hbaseAdmin.disableTable(tableName);
         System.out.println("Table " + new String(tableName) + " disabled");
    }

    public static void dropTable(byte[] tableName) throws IOException {
         HBaseConfiguration hbaseConfig = new HBaseConfiguration();
         HBaseAdmin hbaseAdmin = new HBaseAdmin(hbaseConfig);
         hbaseAdmin.deleteTable(tableName);
         System.out.println("Table " + new String(tableName) + " deleted");
    }
Get Table, Get & Delete Record
public static HTable getTable(byte[] tableName) throws IOException {
     HBaseConfiguration hbaseConfig = new HBaseConfiguration();
     HBaseAdmin hbaseAdmin = new HBaseAdmin(hbaseConfig);
     return new HTable(hbaseConfig, tableName);
}

public static void deleteRecord(HTable hTable, String rowKey)
          throws IOException {
     Delete delete = new Delete(rowKey.getBytes());
     hTable.delete(delete);
     System.out.println("Record " + rowKey + " deleted ");
}

public static PResultSet getRecord(HTable hTable, String rowKey,
          String family) throws IOException {
     Get get = new Get(rowKey.getBytes());
     get.addFamily(family.getBytes());
     PResultSet resultSet = new PResultSet(hTable, get);
     return resultSet;
}
Scan Records
•   public static void scanRecords(byte[] startKey, HTable hTable)
•             throws IOException {
•        Scan scan = new Scan(startKey);
•        ResultScanner resultScanner = hTable.getScanner(scan);

•       System.out.println("#########Scan result ################");
•       for (Result result : resultScanner) {
•            System.out.println(">key is " + new String(result.getRow()));
•            for (KeyValue kv : result.raw()) {
•                 System.out.println(new String(kv.getFamily()) + ":"
•                           + new String(kv.getQualifier()) + " = "
•                           + new String(kv.getValue()));
•            }
•       }
•       System.out.println("--------Scan result ends here-------------------");
•   }
Scan Records by Filter
public static void scanRecords(byte[] startKey, HTable hTable, TestFilter testFilter)
throws IOException {
          Scan scan = new Scan(startKey);

         scan.setFilter(testFilter.getFilters());
         ResultScanner resultScanner = hTable.getScanner(scan);
         System.out.println("#########filter scan result ################");
         for (Result result : resultScanner) {
              System.out.println(">key is " + new String(result.getRow()));
              for (KeyValue kv : result.raw()) {
                   System.out.println(new String(kv.getFamily()) + ":"
                             + new String(kv.getQualifier()) + " = "
                             + new String(kv.getValue()));
              }
         }
         System.out.println("--------Scan result ends here-------------------");
    }
Filter Object
class FilterObject {
     String columnFamilyName;
     String columnName;
     String value;
     CompareOp compareOp;

    public FilterObject(String columnFamilyName, String columnName,
              String value, CompareOp compareOp) {
         this.columnFamilyName = columnFamilyName;
         this.columnName = columnName;
         this.value = value;
         this.compareOp = compareOp;
    }
}
Filter Class
class TestFilter {
     private List<FilterObject> filterObjects;
     private FilterList filterList;

    public TestFilter() {
         filterObjects = new ArrayList<FilterObject>();
         filterList = new FilterList();
    }

    public void addFilterObject(FilterObject ft) {
         filterObjects.add(ft);

    }

    public FilterList getFilters() {
         for (FilterObject filterObject : filterObjects) {
              filterList.addFilter(new SingleColumnValueFilter(
                        filterObject.columnFamilyName.getBytes(),
                        filterObject.columnName.getBytes(), filterObject.compareOp,
                        filterObject.value.getBytes()));
         }
         return filterList;
    }

}
ResultSet
class PResultSet {
        private String tableName;
        private String columnFamily;
        private HashMap<String, String> resutlMap;
        private Result rs;

        public PResultSet(HTable hTable, Get get) throws IOException {
               this.rs = hTable.get(get);
               this.tableName = hTable.getTableDescriptor().getNameAsString();
               this.columnFamily = hTable.getTableDescriptor().getColumnFamilies()
                               .toString();
               this.resutlMap = new HashMap<String, String>();
        }

        public String getTableName() {
                return tableName;
        }

        public void setTableName(String tableName) {
                this.tableName = tableName;
        }

Cont…
ResultSet cont….
public String getColumnFamily() {
          return columnFamily;
     }
     public void setColumnFamily(String columnFamily) {
          this.columnFamily = columnFamily;
     }
     public HashMap<String, String> getResutlMap() {
          return resutlMap;
     }
     public void setResutlMap(HashMap<String, String> resutlMap) {
          this.resutlMap = resutlMap;
     }
     public String toString() {
          System.out.println("TableName :" + getTableName());
          System.out.println("ColumnFamily : " + getColumnFamily());
          System.out.println("No Of Rows : " + rs.size());
          for (KeyValue kv : rs.raw()) {
               resutlMap.put(Bytes.toString(kv.getQualifier()),
                         Bytes.toString(kv.getValue()));
          }
          return resutlMap.toString();
     }
}
Testing Code – Create Functions
Create Table Testing:

               String tableName = "TrainingDB";
               String familyName = "CreditLog";

               byte[] tableNameBytes = tableName.getBytes();
               byte[] familyBytes = familyName.getBytes();

               byte[][] columnFamilyByteArray = new byte[][] { familyBytes };

               if (tableExist(tableNameBytes)) {
                    System.out.println("Table exist");
                    disableTable(tableNameBytes);
                    dropTable(tableNameBytes);
               }

               createTable(tableNameBytes, columnFamilyByteArray, 5);
               HTable hTable = getTable(tableNameBytes);
               System.out.println("Successfully created");
               System.out.println("Column exist : "
                         + columnFamilyExist(hTable, familyBytes));
Testing Code – Put
HashMap<String, HashMap<String, String>> creditLogMaps
          = new HashMap<String, HashMap<String, String>>();
          HashMap<String, String> creditLogMap = new HashMap<String, String>();

         creditLogMap.put("Name", "Karthik");
         creditLogMap.put("Age", "36");
         creditLogMap.put("Rating", "Good");
         creditLogMap.put("Limit", "404$");

         String rowKey = "1753-4343-4322-5423";
         creditLogMaps.put(rowKey, creditLogMap);

         creditLogMap = new HashMap<String, String>();

         creditLogMap.put("Name", "Manik");
         creditLogMap.put("Age", "36");
         creditLogMap.put("Rating", "Average");
         creditLogMap.put("Limit", "-2$");

         String rowKey2 = "5557-4343-4322-5422";

         creditLogMaps.put(rowKey2, creditLogMap);

         insertRecord(hTable, familyBytes, false, creditLogMaps);
Testing Code - Put
HashMap<String, String> transLogMap = new HashMap<String, String>();
     transLogMap.put("Date", "23-NOV-2011");
     transLogMap.put("Amount", "$30");
     transLogMap.put("Balance", "$450");
     transLogMap.put("Bank", "Barclays");

    HashMap<String, HashMap<String, String>> transLogMaps
         = new HashMap<String, HashMap<String, String>>();
    transLogMaps.put(rowKey, transLogMap);
    insertRecord(hTable, "TransLog".getBytes(), true, transLogMaps);
Testing Code – List Tables
System.out.println("Tables in HBase");
     for (String name : getTableNames()) {
          System.out.println("# " + name);
          System.out.println("Table columns");
          HTable table = getTable(name.getBytes());
          for (String columnName : getColumnFamilies(table)) {
               System.out.println("- " + columnName);
          }
     }
Testing Code – Get & Scan Records
  System.out.println(getRecord(hTable, rowKey, familyName).toString());
  System.out.println(getRecord(hTable, rowKey, "TransLog").toString());

  scanRecords(rowKey.getBytes(), hTable);

  FilterObject filterObject = new FilterObject(familyName, "Age", "36",
            CompareOp.EQUAL);
  FilterObject filterObject2 = new FilterObject(familyName, "Limit",
            "-2$", CompareOp.EQUAL);

  TestFilter testFilter = new TestFilter();
  testFilter.addFilterObject(filterObject);
  testFilter.addFilterObject(filterObject2);

  scanRecords(rowKey.getBytes(), hTable, testFilter);

  deleteRecord(hTable, rowKey);

  System.out.println("After delete");
  scanRecords(rowKey.getBytes(), hTable);
Happy Coding
– Mani
– mmaniga@yahoo.co.uk

More Related Content

What's hot

Rデバッグあれこれ
RデバッグあれこれRデバッグあれこれ
Rデバッグあれこれ
Takeshi Arabiki
 
Hidden Treasures of the Python Standard Library
Hidden Treasures of the Python Standard LibraryHidden Treasures of the Python Standard Library
Hidden Treasures of the Python Standard Library
doughellmann
 
The Ring programming language version 1.6 book - Part 46 of 189
The Ring programming language version 1.6 book - Part 46 of 189The Ring programming language version 1.6 book - Part 46 of 189
The Ring programming language version 1.6 book - Part 46 of 189
Mahmoud Samir Fayed
 
はじめてのGroovy
はじめてのGroovyはじめてのGroovy
はじめてのGroovy
Tsuyoshi Yamamoto
 
関数潮流(Function Tendency)
関数潮流(Function Tendency)関数潮流(Function Tendency)
関数潮流(Function Tendency)
riue
 
The Ring programming language version 1.7 book - Part 48 of 196
The Ring programming language version 1.7 book - Part 48 of 196The Ring programming language version 1.7 book - Part 48 of 196
The Ring programming language version 1.7 book - Part 48 of 196
Mahmoud Samir Fayed
 
Adodb Scripts And Some Sample Scripts[1]
Adodb Scripts And Some Sample Scripts[1]Adodb Scripts And Some Sample Scripts[1]
Adodb Scripts And Some Sample Scripts[1]
User1test
 
Tips and Tricks of Developing .NET Application
Tips and Tricks of Developing .NET ApplicationTips and Tricks of Developing .NET Application
Tips and Tricks of Developing .NET Application
Joni
 
Scala 2 + 2 > 4
Scala 2 + 2 > 4Scala 2 + 2 > 4
Scala 2 + 2 > 4
Emil Vladev
 
Grails - The search is over
Grails - The search is overGrails - The search is over
Grails - The search is over
Felipe Coutinho
 
The Ring programming language version 1.4.1 book - Part 13 of 31
The Ring programming language version 1.4.1 book - Part 13 of 31The Ring programming language version 1.4.1 book - Part 13 of 31
The Ring programming language version 1.4.1 book - Part 13 of 31
Mahmoud Samir Fayed
 
Xlab #1: Advantages of functional programming in Java 8
Xlab #1: Advantages of functional programming in Java 8Xlab #1: Advantages of functional programming in Java 8
Xlab #1: Advantages of functional programming in Java 8
XSolve
 
Patterns for slick database applications
Patterns for slick database applicationsPatterns for slick database applications
Patterns for slick database applications
Skills Matter
 
The Ring programming language version 1.5.1 book - Part 24 of 180
The Ring programming language version 1.5.1 book - Part 24 of 180The Ring programming language version 1.5.1 book - Part 24 of 180
The Ring programming language version 1.5.1 book - Part 24 of 180
Mahmoud Samir Fayed
 
The Ring programming language version 1.10 book - Part 54 of 212
The Ring programming language version 1.10 book - Part 54 of 212The Ring programming language version 1.10 book - Part 54 of 212
The Ring programming language version 1.10 book - Part 54 of 212
Mahmoud Samir Fayed
 
[2019-07] GraphQL in depth (serverside)
[2019-07] GraphQL in depth (serverside)[2019-07] GraphQL in depth (serverside)
[2019-07] GraphQL in depth (serverside)
croquiscom
 
JAVA 8 : Migration et enjeux stratégiques en entreprise
JAVA 8 : Migration et enjeux stratégiques en entrepriseJAVA 8 : Migration et enjeux stratégiques en entreprise
JAVA 8 : Migration et enjeux stratégiques en entreprise
SOAT
 
Groovy ネタ NGK 忘年会2009 ライトニングトーク
Groovy ネタ NGK 忘年会2009 ライトニングトークGroovy ネタ NGK 忘年会2009 ライトニングトーク
Groovy ネタ NGK 忘年会2009 ライトニングトーク
Tsuyoshi Yamamoto
 
The Ring programming language version 1.5.4 book - Part 44 of 185
The Ring programming language version 1.5.4 book - Part 44 of 185The Ring programming language version 1.5.4 book - Part 44 of 185
The Ring programming language version 1.5.4 book - Part 44 of 185
Mahmoud Samir Fayed
 
Joker 2015 - Валеев Тагир - Что же мы измеряем?
Joker 2015 - Валеев Тагир - Что же мы измеряем?Joker 2015 - Валеев Тагир - Что же мы измеряем?
Joker 2015 - Валеев Тагир - Что же мы измеряем?
tvaleev
 

What's hot (20)

Rデバッグあれこれ
RデバッグあれこれRデバッグあれこれ
Rデバッグあれこれ
 
Hidden Treasures of the Python Standard Library
Hidden Treasures of the Python Standard LibraryHidden Treasures of the Python Standard Library
Hidden Treasures of the Python Standard Library
 
The Ring programming language version 1.6 book - Part 46 of 189
The Ring programming language version 1.6 book - Part 46 of 189The Ring programming language version 1.6 book - Part 46 of 189
The Ring programming language version 1.6 book - Part 46 of 189
 
はじめてのGroovy
はじめてのGroovyはじめてのGroovy
はじめてのGroovy
 
関数潮流(Function Tendency)
関数潮流(Function Tendency)関数潮流(Function Tendency)
関数潮流(Function Tendency)
 
The Ring programming language version 1.7 book - Part 48 of 196
The Ring programming language version 1.7 book - Part 48 of 196The Ring programming language version 1.7 book - Part 48 of 196
The Ring programming language version 1.7 book - Part 48 of 196
 
Adodb Scripts And Some Sample Scripts[1]
Adodb Scripts And Some Sample Scripts[1]Adodb Scripts And Some Sample Scripts[1]
Adodb Scripts And Some Sample Scripts[1]
 
Tips and Tricks of Developing .NET Application
Tips and Tricks of Developing .NET ApplicationTips and Tricks of Developing .NET Application
Tips and Tricks of Developing .NET Application
 
Scala 2 + 2 > 4
Scala 2 + 2 > 4Scala 2 + 2 > 4
Scala 2 + 2 > 4
 
Grails - The search is over
Grails - The search is overGrails - The search is over
Grails - The search is over
 
The Ring programming language version 1.4.1 book - Part 13 of 31
The Ring programming language version 1.4.1 book - Part 13 of 31The Ring programming language version 1.4.1 book - Part 13 of 31
The Ring programming language version 1.4.1 book - Part 13 of 31
 
Xlab #1: Advantages of functional programming in Java 8
Xlab #1: Advantages of functional programming in Java 8Xlab #1: Advantages of functional programming in Java 8
Xlab #1: Advantages of functional programming in Java 8
 
Patterns for slick database applications
Patterns for slick database applicationsPatterns for slick database applications
Patterns for slick database applications
 
The Ring programming language version 1.5.1 book - Part 24 of 180
The Ring programming language version 1.5.1 book - Part 24 of 180The Ring programming language version 1.5.1 book - Part 24 of 180
The Ring programming language version 1.5.1 book - Part 24 of 180
 
The Ring programming language version 1.10 book - Part 54 of 212
The Ring programming language version 1.10 book - Part 54 of 212The Ring programming language version 1.10 book - Part 54 of 212
The Ring programming language version 1.10 book - Part 54 of 212
 
[2019-07] GraphQL in depth (serverside)
[2019-07] GraphQL in depth (serverside)[2019-07] GraphQL in depth (serverside)
[2019-07] GraphQL in depth (serverside)
 
JAVA 8 : Migration et enjeux stratégiques en entreprise
JAVA 8 : Migration et enjeux stratégiques en entrepriseJAVA 8 : Migration et enjeux stratégiques en entreprise
JAVA 8 : Migration et enjeux stratégiques en entreprise
 
Groovy ネタ NGK 忘年会2009 ライトニングトーク
Groovy ネタ NGK 忘年会2009 ライトニングトークGroovy ネタ NGK 忘年会2009 ライトニングトーク
Groovy ネタ NGK 忘年会2009 ライトニングトーク
 
The Ring programming language version 1.5.4 book - Part 44 of 185
The Ring programming language version 1.5.4 book - Part 44 of 185The Ring programming language version 1.5.4 book - Part 44 of 185
The Ring programming language version 1.5.4 book - Part 44 of 185
 
Joker 2015 - Валеев Тагир - Что же мы измеряем?
Joker 2015 - Валеев Тагир - Что же мы измеряем?Joker 2015 - Валеев Тагир - Что же мы измеряем?
Joker 2015 - Валеев Тагир - Что же мы измеряем?
 

Similar to H base programming

JEEConf 2017 - Having fun with Javassist
JEEConf 2017 - Having fun with JavassistJEEConf 2017 - Having fun with Javassist
JEEConf 2017 - Having fun with Javassist
Anton Arhipov
 
Kamil Chmielewski, Jacek Juraszek - "Hadoop. W poszukiwaniu złotego młotka."
Kamil Chmielewski, Jacek Juraszek - "Hadoop. W poszukiwaniu złotego młotka."Kamil Chmielewski, Jacek Juraszek - "Hadoop. W poszukiwaniu złotego młotka."
Kamil Chmielewski, Jacek Juraszek - "Hadoop. W poszukiwaniu złotego młotka."
sjabs
 
apache tajo 연동 개발 후기
apache tajo 연동 개발 후기apache tajo 연동 개발 후기
apache tajo 연동 개발 후기
효근 박
 
JJUG CCC 2011 Spring
JJUG CCC 2011 SpringJJUG CCC 2011 Spring
JJUG CCC 2011 Spring
Kiyotaka Oku
 
LECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdf
LECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdfLECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdf
LECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdf
ShashikantSathe3
 
JavaOne 2015 - Having fun with Javassist
JavaOne 2015 - Having fun with JavassistJavaOne 2015 - Having fun with Javassist
JavaOne 2015 - Having fun with Javassist
Anton Arhipov
 
Store and Process Big Data with Hadoop and Cassandra
Store and Process Big Data with Hadoop and CassandraStore and Process Big Data with Hadoop and Cassandra
Store and Process Big Data with Hadoop and Cassandra
Deependra Ariyadewa
 
Riga Dev Day 2016 - Having fun with Javassist
Riga Dev Day 2016 - Having fun with JavassistRiga Dev Day 2016 - Having fun with Javassist
Riga Dev Day 2016 - Having fun with Javassist
Anton Arhipov
 
Java 8 Puzzlers [as presented at OSCON 2016]
Java 8 Puzzlers [as presented at  OSCON 2016]Java 8 Puzzlers [as presented at  OSCON 2016]
Java 8 Puzzlers [as presented at OSCON 2016]
Baruch Sadogursky
 
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
Dmitry Soshnikov
 
Answer this question for quality assurance. Include a final applicat.pdf
Answer this question for quality assurance. Include a final applicat.pdfAnswer this question for quality assurance. Include a final applicat.pdf
Answer this question for quality assurance. Include a final applicat.pdf
akanshanawal
 
Cascading Through Hadoop for the Boulder JUG
Cascading Through Hadoop for the Boulder JUGCascading Through Hadoop for the Boulder JUG
Cascading Through Hadoop for the Boulder JUG
Matthew McCullough
 
Scala in practice
Scala in practiceScala in practice
Scala in practice
andyrobinson8
 
ES6 patterns in the wild
ES6 patterns in the wildES6 patterns in the wild
ES6 patterns in the wild
Joe Morgan
 
AJUG April 2011 Cascading example
AJUG April 2011 Cascading exampleAJUG April 2011 Cascading example
AJUG April 2011 Cascading example
Christopher Curtin
 
  package Chapter_20;import ToolKit.PostfixNotation;import javaf.pdf
  package Chapter_20;import ToolKit.PostfixNotation;import javaf.pdf  package Chapter_20;import ToolKit.PostfixNotation;import javaf.pdf
  package Chapter_20;import ToolKit.PostfixNotation;import javaf.pdf
sudhirchourasia86
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
Dmitry Sheiko
 
Clean coding-practices
Clean coding-practicesClean coding-practices
Clean coding-practices
John Ferguson Smart Limited
 
code for quiz in my sql
code for quiz  in my sql code for quiz  in my sql
code for quiz in my sql
JOYITAKUNDU1
 
Productive Programming in Groovy
Productive Programming in GroovyProductive Programming in Groovy
Productive Programming in Groovy
Ganesh Samarthyam
 

Similar to H base programming (20)

JEEConf 2017 - Having fun with Javassist
JEEConf 2017 - Having fun with JavassistJEEConf 2017 - Having fun with Javassist
JEEConf 2017 - Having fun with Javassist
 
Kamil Chmielewski, Jacek Juraszek - "Hadoop. W poszukiwaniu złotego młotka."
Kamil Chmielewski, Jacek Juraszek - "Hadoop. W poszukiwaniu złotego młotka."Kamil Chmielewski, Jacek Juraszek - "Hadoop. W poszukiwaniu złotego młotka."
Kamil Chmielewski, Jacek Juraszek - "Hadoop. W poszukiwaniu złotego młotka."
 
apache tajo 연동 개발 후기
apache tajo 연동 개발 후기apache tajo 연동 개발 후기
apache tajo 연동 개발 후기
 
JJUG CCC 2011 Spring
JJUG CCC 2011 SpringJJUG CCC 2011 Spring
JJUG CCC 2011 Spring
 
LECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdf
LECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdfLECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdf
LECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdf
 
JavaOne 2015 - Having fun with Javassist
JavaOne 2015 - Having fun with JavassistJavaOne 2015 - Having fun with Javassist
JavaOne 2015 - Having fun with Javassist
 
Store and Process Big Data with Hadoop and Cassandra
Store and Process Big Data with Hadoop and CassandraStore and Process Big Data with Hadoop and Cassandra
Store and Process Big Data with Hadoop and Cassandra
 
Riga Dev Day 2016 - Having fun with Javassist
Riga Dev Day 2016 - Having fun with JavassistRiga Dev Day 2016 - Having fun with Javassist
Riga Dev Day 2016 - Having fun with Javassist
 
Java 8 Puzzlers [as presented at OSCON 2016]
Java 8 Puzzlers [as presented at  OSCON 2016]Java 8 Puzzlers [as presented at  OSCON 2016]
Java 8 Puzzlers [as presented at OSCON 2016]
 
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
 
Answer this question for quality assurance. Include a final applicat.pdf
Answer this question for quality assurance. Include a final applicat.pdfAnswer this question for quality assurance. Include a final applicat.pdf
Answer this question for quality assurance. Include a final applicat.pdf
 
Cascading Through Hadoop for the Boulder JUG
Cascading Through Hadoop for the Boulder JUGCascading Through Hadoop for the Boulder JUG
Cascading Through Hadoop for the Boulder JUG
 
Scala in practice
Scala in practiceScala in practice
Scala in practice
 
ES6 patterns in the wild
ES6 patterns in the wildES6 patterns in the wild
ES6 patterns in the wild
 
AJUG April 2011 Cascading example
AJUG April 2011 Cascading exampleAJUG April 2011 Cascading example
AJUG April 2011 Cascading example
 
  package Chapter_20;import ToolKit.PostfixNotation;import javaf.pdf
  package Chapter_20;import ToolKit.PostfixNotation;import javaf.pdf  package Chapter_20;import ToolKit.PostfixNotation;import javaf.pdf
  package Chapter_20;import ToolKit.PostfixNotation;import javaf.pdf
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
 
Clean coding-practices
Clean coding-practicesClean coding-practices
Clean coding-practices
 
code for quiz in my sql
code for quiz  in my sql code for quiz  in my sql
code for quiz in my sql
 
Productive Programming in Groovy
Productive Programming in GroovyProductive Programming in Groovy
Productive Programming in Groovy
 

Recently uploaded

Infrastructure Challenges in Scaling RAG with Custom AI models
Infrastructure Challenges in Scaling RAG with Custom AI modelsInfrastructure Challenges in Scaling RAG with Custom AI models
Infrastructure Challenges in Scaling RAG with Custom AI models
Zilliz
 
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
Neo4j
 
Programming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup SlidesProgramming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup Slides
Zilliz
 
Mind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AIMind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AI
Kumud Singh
 
Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
innovationoecd
 
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
名前 です男
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
DianaGray10
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
Quotidiano Piemontese
 
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Speck&Tech
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
Matthew Sinclair
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
Alpen-Adria-Universität
 
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
SOFTTECHHUB
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
mikeeftimakis1
 
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy SurveyTrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
Kari Kakkonen
 
RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
KAMESHS29
 
Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
DianaGray10
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
Uni Systems S.M.S.A.
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
Octavian Nadolu
 

Recently uploaded (20)

Infrastructure Challenges in Scaling RAG with Custom AI models
Infrastructure Challenges in Scaling RAG with Custom AI modelsInfrastructure Challenges in Scaling RAG with Custom AI models
Infrastructure Challenges in Scaling RAG with Custom AI models
 
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
 
Programming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup SlidesProgramming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup Slides
 
Mind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AIMind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AI
 
Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
 
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
 
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
 
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
 
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy SurveyTrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy Survey
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
 
RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
 
Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
 

H base programming

  • 1. HBase Programming Mani mmaniga@yahoo.co.uk
  • 2. CreateTable public static int VERSION = 5; public static void createTable(byte[] tableName, byte[][] families, int numVersions) throws IOException { HBaseConfiguration hbaseConfig = new HBaseConfiguration(); HBaseAdmin hbaseAdmin = new HBaseAdmin(hbaseConfig); HTableDescriptor htableDesc = new HTableDescriptor(tableName); for (byte[] family : families) { HColumnDescriptor hColumnDescriptor = new HColumnDescriptor(family, numVersions, HColumnDescriptor.DEFAULT_COMPRESSION, HColumnDescriptor.DEFAULT_IN_MEMORY, HColumnDescriptor.DEFAULT_BLOCKCACHE, HColumnDescriptor.DEFAULT_TTL, HColumnDescriptor.DEFAULT_BLOOMFILTER); htableDesc.addFamily(hColumnDescriptor); } hbaseAdmin.createTable(htableDesc); }
  • 3. Table Exists & Get Table Name public static boolean tableExist(byte[] tableName) throws IOException { HBaseConfiguration hbaseConfig = new HBaseConfiguration(); HBaseAdmin hbaseAdmin = new HBaseAdmin(hbaseConfig); return hbaseAdmin.tableExists(tableName); } public static List<String> getTableNames() throws IOException { HBaseConfiguration hbaseConfig = new HBaseConfiguration(); HBaseAdmin hbaseAdmin = new HBaseAdmin(hbaseConfig); List<String> tables = new ArrayList<String>(); for (HTableDescriptor htableDesc : hbaseAdmin.listTables()) { printTableDescriptors(htableDesc); tables.add(htableDesc.getNameAsString()); } return tables; } public static void printTableDescriptors(HTableDescriptor descriptor) { System.out.println("Table name " + descriptor.getNameAsString()); for (HColumnDescriptor columnDescriptor : descriptor.getColumnFamilies()) { System.out.println(columnDescriptor.getNameAsString()); System.out.println(columnDescriptor.getMaxVersions()); System.out.println(columnDescriptor.getMinVersions()); } }
  • 4. Insert Record public static void insertRecord(HTable htable, byte[] columnFamily, boolean createColumnFamily, HashMap<String, HashMap<String, String>> creditLogMaps) throws IOException { String rowKey;// record key HashMap<String, String> columnData; if (!columnFamilyExist(htable, columnFamily)) { if (!createColumnFamily) return; else createColumnFamily(htable, columnFamily, VERSION); } for (Map.Entry<String, HashMap<String, String>> creditLogMap : creditLogMaps.entrySet()) { rowKey = creditLogMap.getKey(); columnData = creditLogMap.getValue(); Put put = new Put(rowKey.getBytes()); for (Map.Entry<String, String> kv : columnData.entrySet()) { put.add(columnFamily, kv.getKey().getBytes(), kv.getValue() .getBytes()); } htable.put(put); System.out.println("Record inserted"); } }
  • 5. Create Column Family public static void createColumnFamily(HTable htable, byte[] columnFamily, int numVersions) throws IOException { disableTable(htable.getTableName()); while (isTableEnabled(htable.getTableName()));// wait untill table is disabled HBaseConfiguration hbaseConfig = new HBaseConfiguration(); HBaseAdmin hbaseAdmin = new HBaseAdmin(hbaseConfig); HColumnDescriptor hColumnDescriptor = new HColumnDescriptor( columnFamily, numVersions, HColumnDescriptor.DEFAULT_COMPRESSION, HColumnDescriptor.DEFAULT_IN_MEMORY, HColumnDescriptor.DEFAULT_BLOCKCACHE, HColumnDescriptor.DEFAULT_TTL, HColumnDescriptor.DEFAULT_BLOOMFILTER); hbaseAdmin.addColumn(htable.getTableName(), hColumnDescriptor); enableTable(htable.getTableName()); }
  • 6. Get Column Family public static List<String> getColumnFamilies(HTable htable) throws IOException { List<String> columnFamilies = new ArrayList<String>(); for (HColumnDescriptor columnDesc : htable.getTableDescriptor().getColumnFamilies()) { columnFamilies.add(columnDesc.getNameAsString()); } return columnFamilies; } public static boolean columnFamilyExist(HTable htable, byte[] columnFamily) throws IOException { boolean hasColumn = false; if (htable.getTableDescriptor().getFamily(columnFamily) != null) { hasColumn = true; } return hasColumn; } public static boolean isTableEnabled(byte[] tableName) throws IOException { HBaseConfiguration hbaseConfig = new HBaseConfiguration(); HBaseAdmin hbaseAdmin = new HBaseAdmin(hbaseConfig); System.out.println("Table enabled " + hbaseAdmin.isTableEnabled(tableName)); return hbaseAdmin.isTableEnabled(tableName); }
  • 7. Enable, Disable & Drop Table public static void enableTable(byte[] tableName) throws IOException { HBaseConfiguration hbaseConfig = new HBaseConfiguration(); HBaseAdmin hbaseAdmin = new HBaseAdmin(hbaseConfig); hbaseAdmin.enableTable(tableName); } public static void disableTable(byte[] tableName) throws IOException { HBaseConfiguration hbaseConfig = new HBaseConfiguration(); HBaseAdmin hbaseAdmin = new HBaseAdmin(hbaseConfig); hbaseAdmin.disableTable(tableName); System.out.println("Table " + new String(tableName) + " disabled"); } public static void dropTable(byte[] tableName) throws IOException { HBaseConfiguration hbaseConfig = new HBaseConfiguration(); HBaseAdmin hbaseAdmin = new HBaseAdmin(hbaseConfig); hbaseAdmin.deleteTable(tableName); System.out.println("Table " + new String(tableName) + " deleted"); }
  • 8. Get Table, Get & Delete Record public static HTable getTable(byte[] tableName) throws IOException { HBaseConfiguration hbaseConfig = new HBaseConfiguration(); HBaseAdmin hbaseAdmin = new HBaseAdmin(hbaseConfig); return new HTable(hbaseConfig, tableName); } public static void deleteRecord(HTable hTable, String rowKey) throws IOException { Delete delete = new Delete(rowKey.getBytes()); hTable.delete(delete); System.out.println("Record " + rowKey + " deleted "); } public static PResultSet getRecord(HTable hTable, String rowKey, String family) throws IOException { Get get = new Get(rowKey.getBytes()); get.addFamily(family.getBytes()); PResultSet resultSet = new PResultSet(hTable, get); return resultSet; }
  • 9. Scan Records • public static void scanRecords(byte[] startKey, HTable hTable) • throws IOException { • Scan scan = new Scan(startKey); • ResultScanner resultScanner = hTable.getScanner(scan); • System.out.println("#########Scan result ################"); • for (Result result : resultScanner) { • System.out.println(">key is " + new String(result.getRow())); • for (KeyValue kv : result.raw()) { • System.out.println(new String(kv.getFamily()) + ":" • + new String(kv.getQualifier()) + " = " • + new String(kv.getValue())); • } • } • System.out.println("--------Scan result ends here-------------------"); • }
  • 10. Scan Records by Filter public static void scanRecords(byte[] startKey, HTable hTable, TestFilter testFilter) throws IOException { Scan scan = new Scan(startKey); scan.setFilter(testFilter.getFilters()); ResultScanner resultScanner = hTable.getScanner(scan); System.out.println("#########filter scan result ################"); for (Result result : resultScanner) { System.out.println(">key is " + new String(result.getRow())); for (KeyValue kv : result.raw()) { System.out.println(new String(kv.getFamily()) + ":" + new String(kv.getQualifier()) + " = " + new String(kv.getValue())); } } System.out.println("--------Scan result ends here-------------------"); }
  • 11. Filter Object class FilterObject { String columnFamilyName; String columnName; String value; CompareOp compareOp; public FilterObject(String columnFamilyName, String columnName, String value, CompareOp compareOp) { this.columnFamilyName = columnFamilyName; this.columnName = columnName; this.value = value; this.compareOp = compareOp; } }
  • 12. Filter Class class TestFilter { private List<FilterObject> filterObjects; private FilterList filterList; public TestFilter() { filterObjects = new ArrayList<FilterObject>(); filterList = new FilterList(); } public void addFilterObject(FilterObject ft) { filterObjects.add(ft); } public FilterList getFilters() { for (FilterObject filterObject : filterObjects) { filterList.addFilter(new SingleColumnValueFilter( filterObject.columnFamilyName.getBytes(), filterObject.columnName.getBytes(), filterObject.compareOp, filterObject.value.getBytes())); } return filterList; } }
  • 13. ResultSet class PResultSet { private String tableName; private String columnFamily; private HashMap<String, String> resutlMap; private Result rs; public PResultSet(HTable hTable, Get get) throws IOException { this.rs = hTable.get(get); this.tableName = hTable.getTableDescriptor().getNameAsString(); this.columnFamily = hTable.getTableDescriptor().getColumnFamilies() .toString(); this.resutlMap = new HashMap<String, String>(); } public String getTableName() { return tableName; } public void setTableName(String tableName) { this.tableName = tableName; } Cont…
  • 14. ResultSet cont…. public String getColumnFamily() { return columnFamily; } public void setColumnFamily(String columnFamily) { this.columnFamily = columnFamily; } public HashMap<String, String> getResutlMap() { return resutlMap; } public void setResutlMap(HashMap<String, String> resutlMap) { this.resutlMap = resutlMap; } public String toString() { System.out.println("TableName :" + getTableName()); System.out.println("ColumnFamily : " + getColumnFamily()); System.out.println("No Of Rows : " + rs.size()); for (KeyValue kv : rs.raw()) { resutlMap.put(Bytes.toString(kv.getQualifier()), Bytes.toString(kv.getValue())); } return resutlMap.toString(); } }
  • 15. Testing Code – Create Functions Create Table Testing: String tableName = "TrainingDB"; String familyName = "CreditLog"; byte[] tableNameBytes = tableName.getBytes(); byte[] familyBytes = familyName.getBytes(); byte[][] columnFamilyByteArray = new byte[][] { familyBytes }; if (tableExist(tableNameBytes)) { System.out.println("Table exist"); disableTable(tableNameBytes); dropTable(tableNameBytes); } createTable(tableNameBytes, columnFamilyByteArray, 5); HTable hTable = getTable(tableNameBytes); System.out.println("Successfully created"); System.out.println("Column exist : " + columnFamilyExist(hTable, familyBytes));
  • 16. Testing Code – Put HashMap<String, HashMap<String, String>> creditLogMaps = new HashMap<String, HashMap<String, String>>(); HashMap<String, String> creditLogMap = new HashMap<String, String>(); creditLogMap.put("Name", "Karthik"); creditLogMap.put("Age", "36"); creditLogMap.put("Rating", "Good"); creditLogMap.put("Limit", "404$"); String rowKey = "1753-4343-4322-5423"; creditLogMaps.put(rowKey, creditLogMap); creditLogMap = new HashMap<String, String>(); creditLogMap.put("Name", "Manik"); creditLogMap.put("Age", "36"); creditLogMap.put("Rating", "Average"); creditLogMap.put("Limit", "-2$"); String rowKey2 = "5557-4343-4322-5422"; creditLogMaps.put(rowKey2, creditLogMap); insertRecord(hTable, familyBytes, false, creditLogMaps);
  • 17. Testing Code - Put HashMap<String, String> transLogMap = new HashMap<String, String>(); transLogMap.put("Date", "23-NOV-2011"); transLogMap.put("Amount", "$30"); transLogMap.put("Balance", "$450"); transLogMap.put("Bank", "Barclays"); HashMap<String, HashMap<String, String>> transLogMaps = new HashMap<String, HashMap<String, String>>(); transLogMaps.put(rowKey, transLogMap); insertRecord(hTable, "TransLog".getBytes(), true, transLogMaps);
  • 18. Testing Code – List Tables System.out.println("Tables in HBase"); for (String name : getTableNames()) { System.out.println("# " + name); System.out.println("Table columns"); HTable table = getTable(name.getBytes()); for (String columnName : getColumnFamilies(table)) { System.out.println("- " + columnName); } }
  • 19. Testing Code – Get & Scan Records System.out.println(getRecord(hTable, rowKey, familyName).toString()); System.out.println(getRecord(hTable, rowKey, "TransLog").toString()); scanRecords(rowKey.getBytes(), hTable); FilterObject filterObject = new FilterObject(familyName, "Age", "36", CompareOp.EQUAL); FilterObject filterObject2 = new FilterObject(familyName, "Limit", "-2$", CompareOp.EQUAL); TestFilter testFilter = new TestFilter(); testFilter.addFilterObject(filterObject); testFilter.addFilterObject(filterObject2); scanRecords(rowKey.getBytes(), hTable, testFilter); deleteRecord(hTable, rowKey); System.out.println("After delete"); scanRecords(rowKey.getBytes(), hTable);
  • 20. Happy Coding – Mani – mmaniga@yahoo.co.uk