0

Problem Statement:-

I am trying to insert data into Cassandra database. I am using Netflix/Astyanax client for this.

Below is the code which will upsert data into Cassandra database using Astyanax client.

In my below method, it accepts two parameter. One is the userId which I will be using as the RowKey and attributes map which will contain, column name as the key and it's column value as the value in the map.

Now how can I use Astyanax client to upsert data into Cassandra database using the below method which accepts those two parameters?

I am mainly concern about attributes Map. How should I use that map to upsert data into Cassandra database?

/**
 * Performs an upsert of the specified attributes for the specified id.
 */
public void upsertAttributes(final String userId, final Map<String, String> attributes) {

    MutationBatch m = CassandraAstyanaxConnection.getInstance().getKeyspace().prepareMutationBatch();

    m.withRow(CassandraAstyanaxConnection.getInstance().getEmp_cf(), userId)
    .putColumn(attributeName from attributesMap, attributeValue from attributesMap, null)
    ;

    try {
        m.execute();
    } catch (ConnectionException e) {
        StringBuilder message = new StringBuilder();
        message.append("Failed to read from C* = '").append(e).append("'. ");

        LOG.error("Failed to write data to C*", e);

        throw new RuntimeException("failed to write data to C*", e);
    }
}
4

1 回答 1

2

您几乎已经给出了解决方案,但我认为您不清楚

 MutationBatch m = CassandraAstyanaxConnection.getInstance().getKeyspace().prepareMutationBatch();
 ColumnListMutation<String> clm = m.withRow(CassandraAstyanaxConnection.getInstance().getEmp_cf(), userId);
 for(String key: attributeMap.keySet()){
     clm.putColumn(key, attributeMap.get(key), null);
 }

try {
    m.execute();
} catch (ConnectionException e) {
    e.printStackTrace();
}

基本上putColumn有不同的重载变体,因此它将支持 cassandra 支持的所有数据类型。

于 2013-04-19T04:18:06.550 回答