从Hector QueryResult对象获取字符串

时间:2013-06-11 06:17:49

标签: java cassandra hector cassandra-cli

我正在使用Java Hector API从Cassandra数据库中检索数据,如下所示:

public static void retrieveData() {
    try {
        //Create a cluster object from your existing Cassandra cluster
        Cluster cluster = HFactory.getOrCreateCluster("Test Cluster", "localhost:9160");

        //Create a keyspace object from the existing keyspace we created using CLI
        Keyspace keyspace = HFactory.createKeyspace("TestDB", cluster);

        SliceQuery<String, String, String> sliceQuery = HFactory.createSliceQuery(keyspace, stringSerializer, stringSerializer, stringSerializer);
        sliceQuery.setColumnFamily("ClientHeaders").setKey("1234");
        sliceQuery.setRange("", "", false, 10);
        sliceQuery.setColumnNames("ip_address","uuid");
        QueryResult<ColumnSlice<String, String>> result = sliceQuery.execute();                 
        System.out.println("\nInserted data is as follows:\n" + result.get());   
    } catch (Exception ex) {
        System.out.println("Error encountered while retrieving data!!");
        ex.printStackTrace() ;
    }

所以我按照以下顺序查询检索到的值:

  

ColumnSlice([HColumn(IP地址= 203.110.85.171),   HColumn(UUID = a3363400-abfd-0130-e2cf-07b5c765964c)])

但是我想在一些字符串变量(string ip = ip_address等)中提取结果并使用。但我不明白该怎么做?请帮忙。感谢。

2 个答案:

答案 0 :(得分:1)

基于Hector的JavaDoc(QueryResultColumnSliceHColumn),您应该可以这样做:

ColumnSlice columnSlice = result.get();
HColumn<String, String> column = columnSlice.getColumnByName("ip_address");
System.out.println("The value of ip_address is " + column.getValue());

或者

for (HColumn<String, String> column : result.get().getColumns()) {
    System.out.println("The value of " + column.getName() + " is " + column.getValue());
}

答案 1 :(得分:1)

尝试这样做:

 if (result != null && result.get() != null) {
            List<HColumn<String, String>> resultCols = result.get().getColumns();
            for (HColumn<String, String> col : resultCols)
            {
               System.out.println(col.getValue());
            }