有没有一种方法可以通过给定的参数构建动态查询?
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)
}