-->

Cassandra 3 Java Driver build dynamic queries

2020-04-19 13:01发布

问题:

Is there a way to build dynamic queries by given parameters?

public List getData(String title,Date dateFrom){
Statement statement = QueryBuilder.select()
                .all().from("test_database", "books");
   if(dateFrom!=null){
       //add clause to statement to find books from 'dateFrom'
   }

}

回答1:

Creating dynamic queries in Cassandra is kind of a code smell. Cassandra isn't really designed for "dynamic" queries, you should be designing tables based on specific query patterns that you need. Dynamic queries can quickly become messy since in Cassandra you'll have to make sure you're following the rules of the WHERE clause so you don't have to use ALLOW FILTERING.

Anyway here's some quick code that should give you an idea of how to do this if it's appropriate for your application:

//build your generic select
        Select select = QueryBuilder.select().all().from("test");

        List<Clause> whereClauses = new ArrayList<>();

        /*
         * Generate Clauses based on a value not being null. Be careful to
         * add the clustering columns in the proper order first, then any index
         */
        if(col1 != null) {
            whereClauses.add(QueryBuilder.eq("col1Name", "col1Val"));
        }

        if(col2 != null) {
            whereClauses.add(QueryBuilder.eq("col2Name", "col2Val"));
        }

        // Add the Clauses and execute or execute the basic select if there's no clauses
        if(!whereClauses.isEmpty()) {
            Select.Where selectWhere = select.where()
            for(Clause clause : whereClauses) {
                selectWhere.and(clause);
            }
            session.execute(selectWhere)
        } else {
            session.execute(select)
        }