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