简体   繁体   English

Cassandra 3 Java Driver构建动态查询

[英]Cassandra 3 Java Driver build dynamic queries

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

}

Creating dynamic queries in Cassandra is kind of a code smell. 在Cassandra中创建动态查询是一种代码味道。 Cassandra isn't really designed for "dynamic" queries, you should be designing tables based on specific query patterns that you need. Cassandra并不是专为“动态”查询而设计的,您应该根据所需的特定查询模式设计表。 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. 动态查询很快就会变得混乱,因为在Cassandra中你必须确保遵循WHERE子句的规则,这样你就不必使用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)
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM