Upsert data into Cassandra database using Astyanax client

微笑、不失礼 提交于 2019-12-13 20:08:23

问题


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

回答1:


You have almost given the solution, but i think its not clear to you

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

Basically putColumn has different overloaded variations, so it will support all the datatypes supported by cassandra.



来源:https://stackoverflow.com/questions/16093881/upsert-data-into-cassandra-database-using-astyanax-client

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!