What is the equivalent of CQL count() in Java driver

Viewed 646

I want to run the following query using Java driver. In CQL, to find count of a partition, I can do select count(*) from table where field1 = “x” ;. What is the equivalent of count() in QueryBuilder? So far, to find the no. of rows returned, I have used

val resultSet = session.execute(partitionSizeQuery)
/*is this the most efficient way to find the size of ResultSet??*/
val resultSetSize = resultSet.all.size

where Query is QueryBuilder.select().from(tableName).where(QueryBuilder.eq("field1", somevalue)). But I am not sure if this is the right way

1 Answers

Equivalent to count() in querybuilder is QueryBuilder.select().countAll(). I would instead just iterate through the resultSet and incrementing a counter as it will page through more slowly while count does some things internally that can fan out the request which can turn into thousands of internal queries (very expensive). Iterating through resultSet is better than all so it wont try to load entire thing into memory if it has to page (result > fetchsize).

Using count is very expensive and there are a few cases you can expect it to timeout. So especially if its something that can be called frequently you sohuld avoid it.

Have you considered using a different table to keep track of entries you added? The extra book keeping is a more work but it will result in efficient queries.

If there are TTLs or something that makes it difficult to track you can also use a job (ie spark or iterating through like above) to just keep the second "count" table, and just have it not up to date all the time.

Related