我在本地设置了一个节点集群。现在我正在尝试从 Cassandra 读取数据。我是 Astyanax(Cassandra 的 Netflix 客户端)的新手。
目前我所看到的是 - 您可以请求基于 rowkey 的数据。意思是基于 rowkey 我可以检索所有不是我想要的列。
但我正在寻找的是 - 我将拥有 rowkey 和几个 columnsNames。因此,根据该行键,我只需要检索这些列。像这样的东西-
SELECT colA, colB from table1 where rowkey = "222";
下面是我根据行键检索所有列名的方法。如何在给定行键的情况下仅检索选定的列?
public void read(final String userId, final Collection<String> columnNames) {
OperationResult<ColumnList<String>> result;
try {
result = CassandraConnection.getInstance().getKeyspace().prepareQuery(CassandraConnection.getInstance().getEmp_cf())
.getKey(userId)
.execute();
ColumnList<String> cols = result.getResult();
for(Iterator<Column<String>> i = cols.iterator(); i.hasNext(); ) {
Column<String> c = i.next();
Object v = null;
if(c.getName().endsWith("id")) // type induction hack
v = c.getIntegerValue();
else
v = c.getStringValue();
System.out.println("- col: '"+c.getName()+"': "+v);
}
} catch (ConnectionException e) {
System.out.println("failed to read from C*" +e);
throw new RuntimeException("failed to read from C*", e);
}
}
在上面的代码中,Collection<String> columnNames
将有几个我想要请求的列名称。
有人可以告诉我需要对上述方法进行哪些更改吗?
最佳答案
为了检索 astyanax 中选定的列,我们必须使用列切片。
List<String> columns = Arrays.asList(new String[]{"col1","col2","col3"});
OperationResult<ColumnList<String>> result = CassandraConnection.getInstance().getKeyspace()
.prepareQuery(CassandraConnection.getInstance().getEmp_cf())
.getKey(userId).withColumnSlice(columns)
.execute();
ColumnList<String> columnList= result.getResult();
for(String col : columns ){
System.out.println(columnList.getColumnByName(col).getStringValue());
}
我假设所有列都是文本类型,所以使用了getStringValue()
,你可以根据你的cf元数据获取它。
干杯
关于java - 如何使用 Astyanax/Netflix 客户端检索给定行键的选定列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16070500/