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

2023-12-06

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

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 并不是真正为“动态”查询而设计的,您应该根据您需要的特定查询模式来设计表。动态查询很快就会变得混乱,因为在 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)
        }
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Cassandra 3 Java 驱动程序构建动态查询 的相关文章

随机推荐