Cassandra Hector: How to retrieve all rows of a column family?

后端 未结 2 1405
温柔的废话
温柔的废话 2020-12-24 15:33

I am looking for a code example to retrieve all rows and all columns of a column family. Something like:

SELECT * FROM MyTable

I see that t

2条回答
  •  自闭症患者
    2020-12-24 16:06

    Try something like this:

    public class Dumper {
        private final Cluster cluster;
        private final Keyspace keyspace;
    
        public Dumper() {
            this.cluster = HFactory.getOrCreateCluster("Name", "hostname");
            this.keyspace = HFactory.createKeyspace("Keyspace", cluster, new QuorumAllConsistencyLevelPolicy());
        }
    
        public void run() {
            int row_count = 100;
    
            RangeSlicesQuery rangeSlicesQuery = HFactory
                .createRangeSlicesQuery(keyspace, UUIDSerializer.get(), StringSerializer.get(), LongSerializer.get())
                .setColumnFamily("Column Family")
                .setRange(null, null, false, 10)
                .setRowCount(row_count);
    
            UUID last_key = null;
    
            while (true) {
                rangeSlicesQuery.setKeys(last_key, null);
                System.out.println(" > " + last_key);
    
                QueryResult> result = rangeSlicesQuery.execute();
                OrderedRows rows = result.get();
                Iterator> rowsIterator = rows.iterator();
    
                // we'll skip this first one, since it is the same as the last one from previous time we executed
                if (last_key != null && rowsIterator != null) rowsIterator.next();   
    
                while (rowsIterator.hasNext()) {
                  Row row = rowsIterator.next();
                  last_key = row.getKey();
    
                  if (row.getColumnSlice().getColumns().isEmpty()) {
                    continue;
                  }
    
    
                  System.out.println(row);
                }
    
                if (rows.getCount() < row_count)
                    break;
            }
        }
    
        public static void main(String[] args) {
            new Dumper().run();
        }
    }
    

    This will page through the column family in pages of 100 rows. It will only fetch 10 columns for each row (you will want to page very long rows too).

    This is for a column family with uuids for row keys, strings for column names and longs for values. Hopefully it should be obvious how to change this.

提交回复
热议问题