使用hector客户端从cassandra检索多个列值

brtdzjyr  于 2021-06-15  发布在  Cassandra
关注(0)|答案(1)|浏览(386)

我和cassandra一起工作,我使用hector客户端读取并向上插入cassandra数据库中的数据。我正在尝试使用hector客户端从cassandra数据库检索数据,如果我只尝试检索一列,我就能够做到这一点。
现在我正在尝试检索 rowKey as 1011 但是用列名作为字符串的集合。下面是我的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数据库中检索特定 rowKey 以及 column c1 . 现在,我尝试从cassandra数据库中检索数据,以收集特定rowkey的列。
意思是这样的-
我想检索多个列但同一行键的数据。如何使用hector客户机进行此操作?我不想检索所有列的数据,然后迭代找出我要查找的各个列的数据。

chhqkbe1

chhqkbe11#

使用由复合键组成的列名作为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());
}

有些地方需要编写逻辑来维护一组记录

相关问题