Cassandra 3 Java Driver构建动态查询

时间:2016-04-05 13:14:16

标签: java cassandra-3.0

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

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 个答案:

答案 0 :(得分:3)

在Cassandra中创建动态查询是一种代码味道。 Cassandra并不是专为“动态”查询而设计的,您应该根据所需的特定查询模式设计表。动态查询很快就会变得混乱,因为在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)
        }
相关问题