Querying Cassandra
The Cassandra module builds CQL statements from Querydsl query types and runs them through the
Apache Cassandra Java driver (org.apache.cassandra:java-driver-core). Query types are generated
from entities annotated for the DataStax object mapper.
Maven Integration
<dependency>
<groupId>io.github.openfeign.querydsl</groupId>
<artifactId>querydsl-cassandra</artifactId>
<version>7.1</version>
</dependency>
Run the annotation processor with maven-compiler-plugin. It brings the mapper annotations with it:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<annotationProcessorPaths>
<path>
<groupId>io.github.openfeign.querydsl</groupId>
<artifactId>querydsl-cassandra-codegen</artifactId>
<version>7.1</version>
</path>
</annotationProcessorPaths>
</configuration>
</plugin>
The entities need org.apache.cassandra:java-driver-mapper-runtime on the compile classpath for
the annotations. The query types do not use it at runtime.
Entities
@Entity
@CqlName("events")
public class Event {
@PartitionKey private String tenant;
@PartitionKey(1) private Integer bucket;
@ClusteringColumn private Instant createdAt;
@ClusteringColumn(1) private Integer seq;
private String title;
private Integer score;
private List<String> tags;
private Map<String, Integer> attributes;
@Transient private String scratch;
// getters and setters
}
The processor generates QEvent, which extends CqlEntityPathBase and uses the usual Querydsl path
types (StringPath, NumberPath, ListPath, …). It also records, for every property:
- the CQL column name, following
@CqlNameand@NamingStrategythe way the mapper does (snake case by default, socreatedAtbecomescreated_at); - whether it is a partition key or clustering column, and its position.
The table name comes from @CqlName on the class, or from the naming strategy. A keyspace given in
@Entity(defaultKeyspace = ...) is used in the generated CQL; otherwise the session keyspace
applies. @Transient, transient fields and @Computed properties are skipped. Records are
supported and are read back through their canonical constructor.
Querying
CassandraQueryFactory factory = new CassandraQueryFactory(session);
QEvent event = QEvent.event;
List<Event> latest = factory.selectFrom(event)
.where(event.tenant.eq("acme"), event.bucket.eq(1),
event.createdAt.gt(since))
.orderBy(event.createdAt.desc())
.limit(10)
.fetch();
Several predicates are combined with and. The following are translated:
| Querydsl | CQL |
|---|---|
eq, lt, loe, gt, goe |
=, <, <=, >, >= |
in(...) |
in (?, ?) |
between(a, b) |
col >= ? and col <= ? |
list.contains(x), set.contains(x) |
col contains ? |
map.containsKey(k), map.containsValue(v) |
col contains key ?, col contains ? |
count(), count(path), min, max, sum, avg |
the CQL aggregate |
CQL has no OR, NOT, !=, LIKE, IS NULL, string functions, joins, subqueries or offsets.
Expressions that use them fail with an UnsupportedOperationException before anything is sent.
orderBy only accepts clustering columns and groupBy only primary key columns.
Results are fetched with fetch(), fetchOne(), fetchFirst(), stream() and fetchCount().
select(...) accepts single paths, several paths (a Tuple) and the usual Projections.
perPartitionLimit(n) adds PER PARTITION LIMIT.
Filtering
Cassandra rejects restrictions on regular columns, or on a partial primary key, because they
require scanning data. allowFiltering() appends ALLOW FILTERING and lets Cassandra run them:
List<Integer> seqs = factory.select(event.seq).from(event)
.where(event.score.gt(15))
.allowFiltering()
.fetch();
Cassandra then reads every partition that might match, which can be a full table scan. Use it for small tables or for queries already restricted to one partition. Columns with a secondary index or SAI index can be queried without it.
Paging
CassandraQuery<Event> query = factory.selectFrom(event)
.where(event.tenant.eq("acme"), event.bucket.eq(1));
CqlPage<Event> page = query.fetchPage(100);
while (page.hasNext()) {
page = query.fetchPage(100, page.safePagingState());
}
safePagingState() is a driver PagingState, and the driver refuses one that belongs to a
different statement. pagingState() is the raw state, which is not checked. A paging state sent
to clients and back can be read and changed by them, so sign it in the application (an HMAC, for
example) and verify it before using it again.
Vector Search
vector<float, n> columns are read and bound as float[]. orderByAnnOf(column, vector) finds
the nearest neighbours through an SAI index; see Querying Vectors.
Errors
When Cassandra rejects a statement, the driver error is rethrown as a QueryException whose message
starts with the generated CQL.
Insert, Update and Delete
factory.insert(event).populate(newEvent).ifNotExists().usingTtl(3600).execute();
factory.update(event)
.set(event.title, "renamed")
.where(event.tenant.eq("acme"), event.bucket.eq(1),
event.createdAt.eq(createdAt), event.seq.eq(0))
.onlyIf(event.score.gt(10))
.execute();
factory.delete(event)
.where(event.tenant.eq("acme"), event.bucket.eq(1),
event.createdAt.goe(cutoff))
.execute();
execute()returns whether the statement was applied. It is only false for lightweight transactions (ifNotExists(),ifExists(),onlyIf(...)) whose condition did not hold.usingTtl(seconds)(insert and update) andusingTimestamp(micros)set the write options.seton a primary key column of an update fails, and update and delete fail unless every partition key column is restricted witheqorin. Cassandra checks everything else.delete(...).deleteColumns(...)deletes single columns instead of rows.populate(bean)skips null properties. Inserts in Cassandra are upserts, so an existing row keeps its old values for those columns. Useset(path, null)to clear a column.onlyIf(...)also acceptsne, which CQL allows inIFconditions but not inWHERE.allowFiltering()does not exist on updates and deletes, because CQL has no such option for them.
Statement options
customizeStatement(UnaryOperator<SimpleStatement>) lets you change the statement before the
driver runs it. You can use this to set things like the consistency level or a timeout. If you
call it more than once, the changes are applied in order. toStatement() gives you the statement
without running it.
Limitations
- Statements are unprepared
SimpleStatements with positional values, so the driver picks the CQL type from the Java value. A value must match its column type: anIntegerbound to abigintcolumn fails, and so do enums inside collections. Enums bound directly are sent as their names. - Values are read with the driver’s default mapping for the column type. The property type must
match it, for example
LongforbigintandIntegerforint. Enums are converted fromtext, but not inside collections. fetchCount()usescount(*). This can time out if a partition is too large. If you usegroupByorperPartitionLimit, the client fetches and counts every row itself.- A paging state is only valid for the exact same statement.
limitapplies to the whole result, across pages. Paramexpressions are rejected, because statements are not prepared.- Template expressions are written into the CQL as given and are not checked against the list of supported operators. Never build them from user input.