Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 36 ยท Java API

Java Client: Put, Get and Delete

Write, read and delete HBase rows with the Java client: Put, Get with versions and time ranges, Result handling, Delete types, atomic increments and conditional updates.

With a Connection and a Table in hand (see Java Client: Connections and Tables), you can do the three basic operations: Put, Get and Delete. Each is a small object you build, configure and hand to the table. This lesson covers each with its options, the Result type that comes back, and the atomic operations that make HBase safe under concurrency.

The real API appears as read-only listings, since there is no cluster here. After each concept comes a runnable Java stand-in that follows the same rules.

Put

A Put is created for one row key, and you add cells to it:

Java
byte[] CF = Bytes.toBytes("info");

Put put = new Put(Bytes.toBytes("u001"));
put.addColumn(CF, Bytes.toBytes("name"), Bytes.toBytes("Jon Snow"));
put.addColumn(CF, Bytes.toBytes("city"), Bytes.toBytes("Oslo"));
table.put(put);

All cells in one Put belong to the same row and are applied atomically: readers see all of them or none. You can give a timestamp per cell with addColumn(family, qualifier, ts, value). A list of puts can be sent in one call, which saves round trips:

Java
List<Put> puts = new ArrayList<>();
for (User u : users) {
    puts.add(new Put(Bytes.toBytes(u.id())).addColumn(CF, Bytes.toBytes("name"), Bytes.toBytes(u.name())));
}
table.put(puts);

Put.setDurability(Durability.SKIP_WAL) skips the write-ahead log (fast, unsafe), and setTTL(ms) gives a cell-level time to live. The write path behind it is in The Write Path.

Get and Result

Java
Get get = new Get(Bytes.toBytes("u001"));
get.addColumn(CF, Bytes.toBytes("name"));        // optional: only this column
Result result = table.get(get);

if (result.isEmpty()) {
    System.out.println("no such row");
} else {
    byte[] raw = result.getValue(CF, Bytes.toBytes("name"));   // newest version, may be null
    String name = Bytes.toString(raw);
}

A Result holds the cells of one row. Useful methods:

  • isEmpty(): no cells found (row missing or no matching columns).
  • getValue(family, qualifier): the newest value or null if absent.
  • getColumnLatestCell(...), getColumnCells(...): cell objects including timestamps.
  • getFamilyMap(family): a NavigableMap<byte[], byte[]> of qualifier to value.
  • rawCells() / listCells(): all cells, with CellUtil.cloneValue(cell) to copy bytes out.
  • getRow(): the row key.

Never ask for a value without checking for null: Bytes.toString(null) returns null, but Bytes.toInt(null) throws.

Options on a Get: readVersions(n) (replaces the old setMaxVersions), setTimeRange(min, max), setTimestamp(ts), setFilter(filter), setCacheBlocks(false), addFamily(cf). In HBase 2.x the old setMaxVersions and HTableDescriptor style names are deprecated or removed; use readVersions and the builders.

To fetch many rows at once, pass a list: Result[] results = table.get(List<Get>). This is much faster than a loop of single gets because the client groups them by RegionServer.

The stand-in below follows the real shape (Put holds cells for one row, Get selects columns and versions, Result answers with isEmpty and getValue).

Java Stand-in: Put, Get and Result

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.

Delete

A Delete writes a tombstone. Its methods differ in how much they hide:

Java
Delete delete = new Delete(Bytes.toBytes("u001"));
delete.addColumn(CF, Bytes.toBytes("city"));      // ONLY the newest version of the cell
// delete.addColumns(CF, Bytes.toBytes("city"));  // ALL versions of the column
// delete.addFamily(CF);                          // the whole family in this row
table.delete(delete);                             // a Delete with no columns deletes the whole row

Notice the one-letter trap: addColumn (singular) removes one version (the latest, or the exact one if you pass a timestamp), while addColumns (plural) removes all versions. Mixing them up is a classic bug. A Delete with nothing added deletes the entire row. Deletes are also atomic per row.

Increment and Append

Counters should be updated on the server, not read and written by the client:

Java
long logins = table.incrementColumnValue(
    Bytes.toBytes("u001"), Bytes.toBytes("stats"), Bytes.toBytes("logins"), 1L);

For several counters in one row, use an Increment object and table.increment(increment). Append adds bytes to a value atomically.

Conditional updates: checkAndMutate

To change a cell only if it still has an expected value (optimistic concurrency), use checkAndMutate. In HBase 2.4 and later, the builder API is:

Java
Put put = new Put(Bytes.toBytes("u001")).addColumn(CF, Bytes.toBytes("version"), Bytes.toBytes(2L));
CheckAndMutateResult res = table.checkAndMutate(
    CheckAndMutate.newBuilder(Bytes.toBytes("u001"))
        .ifEquals(CF, Bytes.toBytes("version"), Bytes.toBytes(1L))
        .build(put));
if (!res.isSuccess()) {
    // somebody else changed it first: re-read and retry
}

ifNotExists creates a cell only if it is absent (a safe "insert if new"). Conditions and mutation must target the same row. For multiple mutations on one row (such as a put plus a delete) use RowMutations.

The stand-in shows the compare-and-set loop that this enables: two "clients" try to update a balance; the loser retries and no update is lost.

Java Stand-in: optimistic updates with check-and-mutate

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.

Error handling

All data-path calls throw IOException. The client retries transient problems itself (region moved, server busy) up to the configured limits, then throws. Typical specific exceptions: RetriesExhaustedException, NoSuchColumnFamilyException (your family name is wrong), TableNotFoundException, RegionTooBusyException (writes blocked, see the write path) and DoNotRetryIOException (retrying will not help). Log the row key and table in your error messages; "put failed" helps nobody.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is true about all cells in a single Put?

    A Put targets one row; HBase guarantees row-level atomicity for it.
  2. 2. What is the difference between Delete.addColumn and Delete.addColumns?

    The singular form targets a single version (the latest by default); the plural form covers all versions.
  3. 3. How should a counter be incremented safely from many clients?

    Client-side read-modify-write loses concurrent updates; server-side increments do not.
  4. 4. What does Result.getValue return for a column that is missing?

    Missing columns return null, so check before converting with Bytes.toInt and similar.
  5. 5. When is checkAndMutate useful?

    It implements compare-and-set for optimistic concurrency on a single row.

Summary

  • Put adds cells to one row atomically; list overloads batch several rows into fewer RPCs.
  • Get plus Result: check isEmpty(), read with getValue, use readVersions and setTimeRange for history.
  • Delete: addColumn (one version) vs addColumns (all) vs addFamily vs the whole row.
  • Use incrementColumnValue/Increment for counters and checkAndMutate for compare-and-set.
  • Expect IOException and handle the specific subclasses deliberately.

Next: Java Client: Scans, Batches and BufferedMutator