javacassandracql

Dynamic prepared statement query for CQL in Java


I have to create CQL queries for multiple tables Java. An example of one such query is:

Statement select = QueryBuilder.select().all().from("MyKeySpace","MyTable")
                                        .where(QueryBuilder.eq("ID", id))
                                        .and(QueryBuilder.eq("NAME", name))
                                        .and(QueryBuilder.eq("STATUS", status))
                                        .and(QueryBuilder.eq("INPUT1", input1))
                                        .and(QueryBuilder.eq("INPUT2", input2))
                                        .allowFiltering();

The problem is that while all the column names are defined for each table, it's not necessary that all the inputs fields are specified by the user and some fields could be null. Thus, I want to create a query dynamically such that it includes only the columns where input is not null. I'm looking for a more efficient way to do this than defining multiple combinations based on non null inputs as that becomes infeasible as more inputs and queries get involved. I also wish to stick to prepared statements for security reasons.


Solution

  • As suggested by @user85421, the problem lies in using Statement as the type for select but since it's an abstract class, I can use Select.Where instead and append and() to the query later. This would look something like:

    Select.Where select = QueryBuilder.select().all().from("MyKeySpace","MyTable")
                                               .where(QueryBuilder.eq("ID", id));
    if (name != null) {
        select = select.and(QueryBuilder.eq("NAME", name));
    }
    ...