我在本地设置了一个节点集群。现在,我正在尝试从Cassandra读取数据。我是Astyanax(Cassandra的Netflix客户端)的新手。

目前,到目前为止,我看到的是-您可以基于行键请求数据。基于rowkey的含义,我可以检索不是我想要的所有列。

但是我正在寻找的是-我将拥有rowkey和几个columnNames。因此,基于该行键,我只需要检索那些列。像这样的东西

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 Client获取给定行键的选定列?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16070500/

10-11 21:44