Skip to content

Writing data

elandau edited this page Nov 29, 2012 · 7 revisions

Data can be written to cassandra either one column at a time or in batches.

Inserting or updating data into Cassandra

Cassandra treats inserts, updates and deletes very similarly as column mutations. Each mutation has a client supplied timestamp (Cassandra assumes all client clocks are synced). When resolving the column value for read cassandra will return the value set for the highest mutation timestamp.

Single column update

keyspace.prepareColumnMutation(CF_STANDARD1, rowKey, "Column1")
    .putValue("1234", null)
    .execute();

Batch mutation

MutationBatch m = keyspace.prepareMutationBatch();

long rowKey = 1234;

// Setting columns in a standard column
m.withRow(CF_STANDARD1, rowKey)
    .putColumn("Column1", "X", null)
    .putColumn("Column2", "X", null);

m.withRow(CF_STANDARD1, rowKey2)
    .putColumn("Column1", "Y", null);

try {
    OperationResult<Void> result = m.execute();
} catch (ConnectionException e) {
    LOG.error(e);
}

The last argument to putColumn is the TTL. TTL is in seconds and is set on a per column basis. The cassandra cluster will automatically delete records after their TTL has expired without the need for any batch cleanup jobs. Setting TTL to null means there is no TTL.

Note: It is not currently possible to set a TTL on counter columns.

Deleting data from Cassandra

MutationBatch m = keyspace.prepareMutationBatch();

// Deleting a standard column
m.withRow(CF_STANDARD1, rowKey)
    .deleteColum("Column1");

// Deleting an entire row
m.withRow(CF_STANDARD1, rowKey2)
    .delete();

try {
    OperationResult<Void> result = m.execute();
} catch (ConnectionException e) {
      LOG.error(e);
}

Write ahead log hook

You can hook into a BatchMutation operation to provide your own WAL functionality. When executing a batch mutation Astyanax will first call the WAL with the mutation, execute the operation, and call either commit or remove to commit the mutation to the WAL on failure or remove from the WAL on success.

MutationBatch m = keyspace
   .prepareMutationBatch()
   .usingWriteAheadLog(writeAheadLog);

// ... fill the mutation

try {
    OperationResult<Void> result = m.execute();
} catch (ConnectionException e) {
    LOG.error(e);
}

How are timestamps specified

TODO

Clone this wiki locally