java—如何使用astyanax/netflix客户端检索给定行键的选定列?

kyvafyod  于 2021-06-14  发布在  Cassandra
关注(0)|答案(1)|浏览(409)

我在本地设置了一个节点集群。现在我正试图读取Cassandra的数据。我对astyanax(cassandra的netflix客户端)是个新手。
目前为止,我看到的是-您可以在rowkey上请求数据。意思是基于rowkey我可以检索所有不是我想要的列。
但我要找的是-我会有rowkey和几个columnsnames。所以基于rowkey,我只需要检索那些列。像这样的-

SELECT colA, colB from table1 where rowkey = "222";

下面是我使用的基于rowkey检索所有列名的方法。如何仅检索给定行键的选定列?

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 将有几个列的名字,我想要求。
有人能告诉我我需要对我的上述方法做些什么改变吗?

mzmfm0qo

mzmfm0qo1#

为了在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元数据拥有它。
干杯

相关问题