【问题标题】:How to retrieve selected columns given a rowkey using Astyanax/Netflix client?如何使用 Astyanax/Netflix 客户端检索给定行键的选定列?
【发布时间】:2013-04-18 14:00:59
【问题描述】:

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

目前我所看到的是-您可以在 rowkey 上请求数据基础。基于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&lt;String&gt; columnNames 将有几个我想要请求的列名。

谁能告诉我我需要对上述方法进行哪些更改?

【问题讨论】:

    标签: java cassandra astyanax


    【解决方案1】:

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

    干杯

    【讨论】:

    • 我还有一个类似的问题,但这次是关于使用 Netflix 客户端 Upsert 插入 Cassandra 数据库。你能帮我吗?感谢您的帮助。
    • @TechGeeky 非常好,会尝试
    • 感谢您的帮助。我在谈论这个post
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-06
    • 2012-08-08
    • 1970-01-01
    • 1970-01-01
    • 2016-04-08
    相关资源
    最近更新 更多