Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 36 ยท Java API

Java Client: The Admin API

Manage HBase from Java with the Admin API: build table and column family descriptors, create pre-split tables, alter schemas, trigger flushes and compactions, and take snapshots.

The Table interface works with data. The Admin interface works with the cluster itself: creating and altering tables, taking snapshots, moving regions, triggering compactions. It is the Java equivalent of the shell commands from Shell: Creating and Altering Tables. You will use it in deployment scripts, migrations and tests.

All HBase calls below are read-only listings (no cluster here). The runnable stand-ins model the builder pattern and the rules Admin enforces.

Getting an Admin

Java
try (Connection connection = ConnectionFactory.createConnection(conf);
     Admin admin = connection.getAdmin()) {
    // administer
}

Admin is lightweight like Table (it shares the connection), is not thread-safe, and should be closed after use. Most operations require the right permissions when security is on (admin or create rights on the namespace).

Descriptors and builders

HBase 2.x removed the mutable HTableDescriptor and HColumnDescriptor classes in favor of immutable descriptors created with builders:

Java
TableName name = TableName.valueOf("shop", "users");

ColumnFamilyDescriptor info = ColumnFamilyDescriptorBuilder
    .newBuilder(Bytes.toBytes("info"))
    .setMaxVersions(3)
    .setTimeToLive(30 * 24 * 3600)                       // seconds
    .setCompressionType(Compression.Algorithm.SNAPPY)
    .setBloomFilterType(BloomType.ROW)
    .setBlocksize(64 * 1024)
    .setInMemory(false)
    .build();

TableDescriptor descriptor = TableDescriptorBuilder
    .newBuilder(name)
    .setColumnFamily(info)
    .setMaxFileSize(10L * 1024 * 1024 * 1024)
    .build();

Builder methods mirror shell options (VERSIONS, TTL, COMPRESSION, BLOOMFILTER, BLOCKSIZE, IN_MEMORY). Because descriptors are immutable, to change something you create a new descriptor from the existing one with ColumnFamilyDescriptorBuilder.newBuilder(existing).

Creating tables

Java
if (!admin.tableExists(name)) {
    admin.createTable(descriptor);                       // one region
}

byte[][] splits = { Bytes.toBytes("2"), Bytes.toBytes("4"), Bytes.toBytes("6"), Bytes.toBytes("8") };
admin.createTable(descriptor, splits);                   // pre-split into 5 regions

admin.createTable(descriptor, Bytes.toBytes("00"), Bytes.toBytes("ff"), 16);  // 16 regions between two keys

createTable waits until all regions are assigned, so the table is usable when it returns. Wrap creation in an tableExists check or catch TableExistsException, so deployments can be re-run safely (idempotent).

Namespaces: admin.createNamespace(NamespaceDescriptor.create("shop").build()), admin.listNamespaces(), admin.deleteNamespace("shop").

Altering schemas

Java
// add a family
admin.addColumnFamily(name, ColumnFamilyDescriptorBuilder.of("prefs"));

// change a family: start from the current definition
ColumnFamilyDescriptor current = admin.getDescriptor(name).getColumnFamily(Bytes.toBytes("info"));
ColumnFamilyDescriptor changed = ColumnFamilyDescriptorBuilder.newBuilder(current).setMaxVersions(10).build();
admin.modifyColumnFamily(name, changed);

// remove a family (data in it goes away)
admin.deleteColumnFamily(name, Bytes.toBytes("prefs"));

Use modifyColumnFamily rather than modifyTable for a single-family change: modifyTable replaces the whole descriptor and silently drops anything you forgot to include.

Disable, enable, delete

Java
admin.disableTable(name);      // closes all regions; table unavailable
admin.deleteTable(name);       // must be disabled first
admin.enableTable(name);       // after a modify that needs it
admin.truncateTable(name, true);   // true = preserve region splits

isTableEnabled, isTableDisabled and isTableAvailable report state. disableTable on a very large table can take a while because every region must close.

Maintenance operations

Java
admin.flush(name);                    // write all MemStores of the table to HFiles
admin.compact(name);                  // request a minor compaction
admin.majorCompact(name);             // request a major compaction (heavy I/O)
admin.split(name, Bytes.toBytes("m"));   // split regions at a key
admin.balance();                      // run the balancer once
admin.balancerSwitch(false, true);    // turn the automatic balancer off, e.g. during maintenance
admin.move(regionEncodedName);        // move a region to a random server

These calls are asynchronous requests: they return as soon as the Master or server accepts them; the work happens later. In HBase 2.x many methods have ...Async variants returning a Future that you can wait on. Use admin.getCompactionState(name) to see whether a compaction is still running.

Snapshots

Java
admin.snapshot("users-2025-01-15", name);
admin.cloneSnapshot("users-2025-01-15", TableName.valueOf("shop", "users_copy"));
admin.disableTable(name);
admin.restoreSnapshot("users-2025-01-15");
admin.enableTable(name);
admin.deleteSnapshot("users-2025-01-15");
List<SnapshotDescription> all = admin.listSnapshots();

The concepts are the same as in Shell: Namespaces, TTL and Snapshots.

Cluster information

Java
ClusterMetrics metrics = admin.getClusterMetrics();
System.out.println(metrics.getLiveServerMetrics().size() + " live servers");
List<TableName> tables = Arrays.asList(admin.listTableNames());

Use these for health checks. A monitoring script can compare live servers with the expected count, or regions per server with a threshold.

Async API (briefly)

HBase 2.x also has a non-blocking client: ConnectionFactory.createAsyncConnection(conf) returns a CompletableFuture<AsyncConnection>, from which you get AsyncTable and AsyncAdmin. Every operation returns a CompletableFuture, which composes with thenApply/thenCompose:

Java
AsyncConnection conn = ConnectionFactory.createAsyncConnection(conf).get();
AsyncTable<?> table = conn.getTable(TableName.valueOf("users"));
table.get(new Get(Bytes.toBytes("u001")))
     .thenAccept(result -> System.out.println(Bytes.toString(result.getValue(CF, Q))));

It suits reactive services and high fan-out, but the blocking Table API is simpler and fine for most programs.

Stand-in: builders and an idempotent deployment

This runnable example uses Java records and a builder in the style of TableDescriptorBuilder, and an Admin that is idempotent: running the deployment twice does not fail. It also shows why immutable descriptors need "copy and change".

Java Stand-in: descriptor builders and idempotent create

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Stand-in: a health check

A final stand-in shows the style of a cluster health check built from ClusterMetrics-like data: it compares live servers and regions per server with limits and prints warnings.

Java Stand-in: a cluster health check

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Common mistakes

  • Using modifyTable to change one family, which can drop other settings. Prefer modifyColumnFamily.
  • Assuming maintenance calls are synchronous. majorCompact only requests the work.
  • Creating tables from every application instance at startup, racing each other. Do it in a deployment step or catch TableExistsException.
  • Forgetting to close Admin.
  • Running majorCompact on a busy cluster at peak hours.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In HBase 2.x, how do you build a table descriptor?

    Descriptors are immutable in 2.x and are created with builders.
  2. 2. Which call changes only one column family without touching the others?

    modifyTable replaces the whole descriptor; modifyColumnFamily updates just the named family.
  3. 3. What does admin.majorCompact(tableName) do?

    Maintenance calls submit a request; use getCompactionState to watch the progress.
  4. 4. How can you make table creation safe to run twice?

    A guard makes the deployment idempotent.
  5. 5. Which snapshot sequence restores a table to an earlier state?

    Restore needs the table disabled; enable it again afterwards.

Summary

  • Admin manages tables, namespaces, snapshots and maintenance; get it from the Connection and close it.
  • Descriptors are immutable and created with TableDescriptorBuilder and ColumnFamilyDescriptorBuilder.
  • Pre-split with createTable(descriptor, splitKeys); guard creation so deployments can be repeated.
  • Use modifyColumnFamily for single-family changes; maintenance operations are asynchronous requests.
  • The async client (CompletableFuture based) exists for reactive applications.

Next: the track page, Apache HBase