Search code examples
sqlintellij-ideacassandracqldatastax-java-driver

Select specific columns plus avg and max using the aliased chainable convenience methods in datastax Java driver for Cassandra


Say I have this general SQL query using the convenience methods of the driver:

statement = select().from(keyspace, table)
            .where(eq("fieldx", var1))
            .and(eq("fieldy", var2))
            .orderBy(asc("fieldz"));
return client.getSession().execute(statement);

and how would I rework the query above to support this kind of CQL/SQL:

select fielda, fieldb, avg(fieldc), max(fielde) from ...

using IntelliJ, I notice after the select(). I can only chain it to append a column() to filter query for specific columns, but I don't see available option for avg() and max(). Looking at the JavaDocs, looks like those should exist? Or I'm not using the right select() method where it's available (I'm a novice to Cassandra and this Java driver). Using goto declaration from the IDE, I see the select() method leads to the QueryBuilder class's static select() method that returns a SelectionOrAlias() method which matches up with the JavaDocs for available methods from that class.

For imports these are the non-custom classes that are imported w.r.t. the driver:

import com.datastax.driver.core.ResultSet;
import com.datastax.driver.core.Statement;
import com.google.inject.Inject;
import static com.datastax.driver.core.querybuilder.QueryBuilder.*;

what am I missing for the right query setup?


Solution

  • The common aggregate methods in CQL have been available in QueryBuilder since 3.3.0 / dse 1.3.0 (JAVA-1443). Here's how you would use them:

    import com.datastax.driver.core.Statement;
    
    import static com.datastax.driver.core.querybuilder.QueryBuilder.*;
    
    public class Example {
    
        public static void main(String args[]) {
            Statement statement = select("fielda",
                    "fieldb",
                    avg("fieldc"),
                    max("fielde"))
                    .from("tbl");
    
            System.out.println(statement);
        }
    }
    

    This yields: SELECT fielda,fieldb,avg(fieldc),max(fielde) FROM tbl;