Skip to content

Writing data

elandau edited this page Nov 29, 2012 · 7 revisions

Inserting data into Cassandra

Simple 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.

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);
}

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);
}
Clone this wiki locally