10

I'm trying to get the number of key value pairs in a Cassandra column family. Following is the code I used.

PreparedStatement statement = client.session
            .prepare("select count(*) from corpus.word_usage");
ResultSet results = client.session.execute(statement.bind());   
Row row = results.one();
System.out.println(row.getVarint(0));

But when I ran this code, I'm getting following exception.

Exception in thread "main" com.datastax.driver.core.exceptions.InvalidTypeException: Column count is of type bigint
   at com.datastax.driver.core.ColumnDefinitions.checkType(ColumnDefinitions.java:291)
   at com.datastax.driver.core.ArrayBackedRow.getVarint(ArrayBackedRow.java:185)
   at SimpleClient.main(SimpleClient.java:57)

According to datastax documentation (http://www.datastax.com/drivers/java/2.0/com/datastax/driver/core/Row.html) getVarint should return a BigInteger. So why I am getting a exception here? What an I doing wrong?

Chamila Wijayarathna
  • 1,815
  • 5
  • 30
  • 54

3 Answers3

12

You can get value as a long, instead.

I couldn't test it but could you try this:

PreparedStatement statement = client.session.prepare("select count(*) from corpus.word_usage");
ResultSet results = client.session.execute(statement.bind());   
Row row = results.one();
long expected = row.getLong("count");
Semih Eker
  • 2,389
  • 1
  • 20
  • 29
  • Link is dead. You might want to check that. – kfkhalili Jan 21 '20 at 14:11
  • The **bigint Cassandra type is mapped with long** Java Type. Documentation link: [CQL to Java type mapping](https://docs.datastax.com/en/developer/java-driver/3.1/manual/#cql-to-java-type-mapping) @kfkhalili – Miguel M. Serrano Nov 18 '20 at 14:55
0

Following worked. I'm not sure why it is working though.

row.getLong(0)
Chamila Wijayarathna
  • 1,815
  • 5
  • 30
  • 54
  • It works because the aggregate function count(*) actually returns an int (which is a long in Java terms) not a varint (which would be a BigInteger in Java). Apparantly you can't have more than 2^63 rows in a table, but that should be enough. – sme Dec 11 '14 at 13:40
  • It works because cassandra bigint is mapped with long java type. Full documentation link with Cassandra-Java mapping types: https://stackoverflow.com/a/64895551/7598367 – Miguel M. Serrano Nov 18 '20 at 14:57
0

The bigint in Cassandra is mapped with long Java Type. Documentation: CQL to Java type mapping.

In your case:

row.getLong(0)