Cassandra 3 Java驱动程序构建动态查询 [英] Cassandra 3 Java Driver build dynamic queries

查看:93
本文介绍了Cassandra 3 Java驱动程序构建动态查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种通过给定参数构建动态查询的方法?

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

}


推荐答案

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

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

这篇关于Cassandra 3 Java驱动程序构建动态查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆