简体   繁体   中英

How to retrieve selected columns given a rowkey using Astyanax/Netflix client?

I have setup one node cluster locally. And now I am trying to read data from Cassandra. I am new to Astyanax(Netflix client for Cassandra).

Currently what I have seen so far is- you can request data basis on the rowkey. Meaning basis on rowkey I can retrieve all the columns which is not what I want.

But what I am looking for is- I will be having rowkey and few columnsNames. So basis on that rowkey, I need to retrieve those columns only. something like this-

SELECT colA, colB from table1 where rowkey = "222";

Below is the method I have that is retrieving all the column names basis on the rowkey. How can I retrieve only selected columns given a row key?

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);
    }


}

In the above code, Collection<String> columnNames will have few column names that I want tor request.

Can anybody tell me what changes I need to make in my above method?

For retrieving selected columns in astyanax we have to use column slice.

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());
        }

I have assumed all the columns as text type, so used getStringValue() , you can have it according to your cf metadata.

Cheers

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM