Cassandra 3 Java 驱动程序构建动态查询

Cassandra 3 Java Driver build dynamic queries

有没有办法通过给定参数构建动态查询?

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'
   }

}

在 Cassandra 中创建动态查询有点代码味道。 Cassandra 并不是真正为 "dynamic" 查询而设计的,您应该根据您需要的特定查询模式来设计表。动态查询很快就会变得混乱,因为在 Cassandra 中,您必须确保遵循 WHERE 子句的规则,这样您就不必使用 ALLOW FILTERING。

无论如何,如果它适合您的应用程序,这里有一些快速代码可以让您了解如何执行此操作:

//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)
        }