CassandraTemplate基于timeuuid查询最近5分钟数据的实现方案
实现方法
Cassandra原生提供了minTimeuuid()、maxTimeuuid()内置函数,可直接将timestamp转换为对应时间边界的timeuuid值,无需手动解析timeuuid的时间部分,查询写法和timestamp场景几乎一致。
代码示例(基于Java Cassandra驱动)
import java.time.LocalDateTime; import java.sql.Timestamp; import static com.datastax.oss.driver.api.querybuilder.QueryBuilder.*; // 计算5分钟前的时间阈值 LocalDateTime thresholdTime = LocalDateTime.now().minusMinutes(5); // 构造查询条件:created_at 大于等于5分钟前对应的最小timeuuid Select.Where select = select(COLUMNS) .from(VIEW) .where(gte("created_at", minTimeuuid(Timestamp.valueOf(thresholdTime))));
补充说明
minTimeuuid(时间戳)会返回指定时间点对应的最小合法timeuuid,所有该时间点及之后生成的timeuuid都会大于这个值,完全匹配「查询某时间点之后数据」的需求- 如果需要查询固定时间区间的数据,可同时设置上下界:
LocalDateTime startTime = LocalDateTime.now().minusMinutes(10); LocalDateTime endTime = LocalDateTime.now().minusMinutes(5); Select.Where select = select(COLUMNS) .from(VIEW) .where( gte("created_at", minTimeuuid(Timestamp.valueOf(startTime))), lt("created_at", minTimeuuid(Timestamp.valueOf(endTime))) ); - 该查询可以正常命中
created_at字段的索引,性能和timestamp类型的范围查询一致,无额外损耗
内容的提问来源于stack exchange,提问作者T Anna
相关产品推荐
相关产品推荐

