我已开始使用Cassandra database
。我打算将Datastax API用于upsert/read
进/出Cassandra database
。我对这个Datastax API
(它使用新的二进制协议)完全不熟悉,我也找不到很多具有适当例子的文档。
create column family profile
with key_validation_class = 'UTF8Type'
and comparator = 'UTF8Type'
and default_validation_class = 'UTF8Type'
and column_metadata = [
{column_name : crd, validation_class : 'DateType'}
{column_name : lmd, validation_class : 'DateType'}
{column_name : account, validation_class : 'UTF8Type'}
{column_name : advertising, validation_class : 'UTF8Type'}
{column_name : behavior, validation_class : 'UTF8Type'}
{column_name : info, validation_class : 'UTF8Type'}
];
现在,下面是我使用Singleton class
连接到Cassandra数据库创建的Datastax API
,它使用了新的二进制协议 -
public class CassandraDatastaxConnection {
private static CassandraDatastaxConnection _instance;
protected static Cluster cluster;
protected static Session session;
public static synchronized CassandraDatastaxConnection getInstance() {
if (_instance == null) {
_instance = new CassandraDatastaxConnection();
}
return _instance;
}
/**
* Creating Cassandra connection using Datastax API
*
*/
private CassandraDatastaxConnection() {
try{
cluster = Cluster.builder().addContactPoint("localhost").build();
session = cluster.connect("my_keyspace");
} catch (NoHostAvailableException e) {
throw new RuntimeException(e);
}
}
public static Cluster getCluster() {
return cluster;
}
public static Session getSession() {
return session;
}
}
第一个问题 - 让我知道在使用使用新二进制协议的Datastax API与Cassandra数据库建立连接时,我是否遗漏了上述singleton class
中的任何内容。
第二个问题 - 现在我正试图upsert and read data
进入/来自Cassandra数据库 -
这些是我在DAO中使用的方法,它将使用上面的Singleton类 -
public Map<String, String> getColumnNames(final String userId, final Collection<String> columnNames) {
//I am not sure what I am supposed to do here?
//Given a userId, I need to retrieve those columnNames from the Cassandra database
//And then put it in the map with column name and its value and then finally return the map
Map<String, String> attributes = new ConcurrentHashMap<String, String>();
for(String col : columnNames ) {
attributes.put(col, colValue);
}
return attributes;
}
/**
* Performs an upsert of the specified attributes for the specified id.
*/
public void upsertAttributes(final String userId, final Map<String, String> columnNameAndValue) {
//I am not sure what I am supposed to do here to upsert the data in Cassandra database.
//Given a userId, I need to upsert the columns values into Cassandra database.
//columnNameAndValue is the map which will have column name as the key and corresponding column value as the value.
}
任何人都可以帮我吗?我对这个使用新二进制协议的Datastax API完全不熟悉,因此在这方面存在很多问题。
感谢您的帮助。
答案 0 :(得分:2)
在您的cassandra.yaml文件中查找标记 start_native_transport ,默认情况下已禁用,启用它。
使用Datastax Java Driver非常类似于jdbc驱动程序。
广告代码
String query = "insert into test(key,col1,col2) values('1','value1','value2')";
session.execute(query);
阅读Cassandra
String query="select * from test;";
ResultSet result = session.execute(query);
for (Row rows: result){
System.out.println(rows.getString("key"));
}