Cassandra 3 Java Driver build dynamic queries

后端 未结 1 378
一整个雨季
一整个雨季 2021-01-24 05:24

Is there a way to build dynamic queries by given parameters?

public List getData(String title,Date dateFrom){
Statement statement = QueryBuilder.select()
               


        
1条回答
  •  清酒与你
    2021-01-24 05:39

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

    0 讨论(0)
提交回复
热议问题