HBase – Listing Table

Listing a Table using HBase Shell

list is the command that is used to list all the tables in HBase. Given below is the syntax of the list command.

hbase(main):001:0 > list

When you type this command and execute in HBase prompt, it will display the list of all the tables in HBase as shown below.

hbase(main):001:0> list
TABLE
emp

Here you can observe a table named emp.

Listing Tables Using Java API

Follow the steps given below to get the list of tables from HBase using java API.

Step 1

You have a method called listTables() in the class HBaseAdmin to get the list of all the tables in HBase. This method returns an array of HTableDescriptor objects.

//creating a configuration object
Configuration conf = HBaseConfiguration.create();

//Creating HBaseAdmin object
HBaseAdmin admin = new HBaseAdmin(conf);

//Getting all the list of tables using HBaseAdmin object
HTableDescriptor[] tableDescriptor = admin.listTables();

Step 2

You can get the length of the HTableDescriptor[] array using the length variable of the HTableDescriptor class. Get the name of the tables from this object using getNameAsString() method. Run the ‘for’ loop using these and get the list of the tables in HBase.

Given below is the program to list all the tables in HBase using Java API.

import java.io.IOException;

import org.apache.hadoop.conf.Configuration;

import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.MasterNotRunningException;
import org.apache.hadoop.hbase.client.HBaseAdmin;

public class ListTables {

   public static void main(String args[])throws MasterNotRunningException, IOException{

      // Instantiating a configuration class
      Configuration conf = HBaseConfiguration.create();

      // Instantiating HBaseAdmin class
      HBaseAdmin admin = new HBaseAdmin(conf);

      // Getting all the list of tables using HBaseAdmin object
      HTableDescriptor[] tableDescriptor = admin.listTables();

      // printing all the table names.
      for (int i=0; i<tableDescriptor.length;i++ ){
         System.out.println(tableDescriptor[i].getNameAsString());
      }
   
   }
}

Compile and execute the above program as shown below.

$javac ListTables.java
$java ListTables

The following should be the output:

User
emp

Leave a Reply