问题陈述:-
我正在尝试将数据插入 Cassandra 数据库。我为此使用 Netflix/Astyanax 客户端
。
下面的代码将使用 Astyanax 客户端
将数据更新插入
到Cassandra 数据库
中。
在我的下面的方法中,它接受两个参数。一个是 userId
,我将用作 RowKey
和 attributes
映射,其中将包含 column name
作为键及其列值
作为 map 中的值。
现在我如何使用 Astyanax 客户端
使用以下接受这两个参数的方法将数据插入
到 Cassandra 数据库中?
我主要关心attributes
Map。我应该如何使用该映射将数据upsert
到 Cassandra 数据库中?
/**
* 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);
}
}
最佳答案
你几乎已经给出了解决方案,但我认为你还不清楚
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支持的所有数据类型。
关于java - 使用 Astyanax 客户端将数据更新到 Cassandra 数据库中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16093881/