2013-04-17 23 views
0

我已经在本地设置了一个节点群集。现在我试图从卡桑德拉读取数据。我是Astyanax(Cassandra的Netflix客户端)的新手。如何使用Astyanax/Netflix客户端检索选定列的行?

目前我目前看到的是 - 您可以在rowkey上请求数据基础。在rowkey上的含义基础我可以检索所有不是我想要的列。

但是我正在寻找的是 - 我将有rowkey和少columnNames。因此,根据该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将有几个列名称,我想tor请求。

有人能告诉我在上述方法中需要做些什么改变吗?

回答

2

要检索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元数据有它。

Cheers

+0

Thanks abhi。得到了那个工作。赞赏你的帮助。 – ferhan

+0

我还有一个类似的问题,但这次是使用Netflix客户端将Upsert插入Cassandra数据库。你能帮我吗?谢谢您的帮助。 – ferhan

+0

@TechGeeky suerly,会尝试 – abhi

相关问题