Cassandra 3 Java Driver build dynamic queries

巧了我就是萌 提交于 2019-12-02 05:34:57

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)
        }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!