【问题标题】:Retrieve multiple columns value from Cassandra using Hector client使用 Hector 客户端从 Cassandra 检索多列值
【发布时间】:2013-05-23 22:12:21
【问题描述】:

我正在使用 Cassandra,并且正在使用 Hector 客户端读取和更新 Cassandra 数据库中的数据。我正在尝试使用 hector 客户端从 Cassandra 数据库中检索数据,如果我只想检索一列,我就可以做到这一点。

现在我正在尝试检索 rowKey as 1011 的数据,但使用 columnNames 作为字符串集合。下面是我的 API,它将使用 Hector 客户端从 Cassandra 数据库中检索数据-

public Map<String, String> getAttributes(String rowKey, Collection<String> attributeNames, String columnFamily) {

    final Cluster cluster = CassandraHectorConnection.getInstance().getCluster();       
    final Keyspace keyspace = CassandraHectorConnection.getInstance().getKeyspace();

    try {

        ColumnQuery<String, String, String> columnQuery = HFactory
                .createStringColumnQuery(keyspace)
                .setColumnFamily(columnFamily).setKey(rowKey)
                .setName("c1");

        QueryResult<HColumn<String, String>> result = columnQuery.execute();
        System.out.println("Column Name from cassandra: " + result.get().getName() + "Column value from cassandra: " + result.get().getValue());

    } catch (HectorException e) {
        LOG.error("Exception in CassandraHectorClient::getAttributes " +e+ ", RowKey = " +rowKey+ ", Attribute Names = " +attributeNames);
    } finally {
        cluster.getConnectionManager().shutdown();
    }


    return null;

}

如果您看到我上面的方法,我正在尝试从 Cassandra 数据库中检索特定 rowKeycolumn c1 的数据。现在我正在尝试从 Cassandra 数据库中检索数据以收集特定 rowKey 的列。

意思是这样的-

我想检索多个列的数据,但使用相同的 rowKey。如何使用 Hector 客户端执行此操作?而且我不想检索所有列的数据,然后迭代以找出我正在寻找的各个列数据。

【问题讨论】:

    标签: java cassandra hector


    【解决方案1】:

    使用由复合键组成的列名作为 UTF8Type 和 TIMEUUID 的组合 然后在

    sliceQuery.setKey("your row key");
    
    Composite startRange = new Composite();
    startRange.addComponent(0, "c1",Composite.ComponentEquality.EQUAL);
    
    Composite endRange = new Composite();
    endRange.addComponent(0, "c1",Composite.ComponentEquality.GREATER_THAN_EQUAL);
    
    sliceQuery.setRange(startRange,endRange, false, Integer.MAX_VALUE);
    
    QueryResult<ColumnSlice<Composite, String>> result = sliceQuery.execute();
    ColumnSlice<Composite, String> cs = result.get();
    

    以上代码将为您提供行键的所有记录 之后迭代如下

    for (HColumn<Composite, String> col : cs.getColumns()) {
    System.out.println("column key's first part : "+col.getName().get(0, HFactoryHelper.stringSerializer).toString());
    System.out.println("column key's second part : "+col.getName().get(1, HFactoryHelper.uuidSerializer).toString());
    System.out.println("column key's value : "+col.getValue());
    }
    

    有些地方你必须编写逻辑来维护记录集

    【讨论】:

      猜你喜欢
      • 2012-04-23
      • 2012-12-07
      • 2012-03-12
      • 2012-03-12
      • 2014-02-23
      • 2011-11-15
      • 2012-01-15
      • 2012-07-04
      • 2012-01-16
      相关资源
      最近更新 更多