How to query count from a cassandra table using the DataStax Java Driver

Querying the count of rows from a Cassandra table in a Java application could be a bit tricky, because you can’t use the com.datastax.driver.mapping.Result<T> return type with the returned Long value returned by the count.

If you are trying to do that you could get an exception containing something like this:

@Table annotation was not found on class java.lang.Long

Yes the Result<T> type can only be used if you have a @Table annotated class. But this solution is not for returning counts.

To return the count, you have to use com.datastax.driver.core.ResultSet as your return type. You could have a query like this in your @Accessor interface.

@Accessor
public interface MyAccessor {

    @Query("SELECT COUNT(*) FROM tableName")
    ResultSet countAll();

}

Then, in your DAO, where you use this accessor, you can do the following to get the long value:

long count = this.myAccessor.countAll().one().getLong(0);