Timothy,
To access the timestamp of the record, you can use a transformValues()
operation.
The ValuesTransformer
you supply has access to the ProcessorContext
and you can call ProcessorContex.timestamp()
in the ValueTransformer.transform()
method.
If the timestamp is within the desired range, return the record otherwise return null. Then add a filter()
after the transformValues()
to remove the records you've rejected.
Here's an example I think will work
class GroupByTimestampExample {
public static void main(String[] args) {
final StreamsBuilder builder = new StreamsBuilder();
// You need to update the the time fields these are just placeholders
long earliest = Instant.now().toEpochMilli();
long latest = Instant.now().toEpochMilli() + (60 * 60 * 1000);
final ValueTransformerSupplier<String, String> valueTransformerSupplier = new TimeFilteringTransformer(earliest, latest);
final KTable<String, Long> voteTable = builder.<String, String>stream("topic")
.transformValues(valueTransformerSupplier)
.filter((k, v) -> v != null)
.groupByKey()
.count();
}
static final class TimeFilteringTransformer implements ValueTransformerSupplier<String, String> {
private final long earliest;
private final long latest;
public TimeFilteringTransformer(final long earliest, final long latest) {
this.earliest = earliest;
this.latest = latest;
}
@Override
public ValueTransformer<String, String> get() {
return new ValueTransformer<String, String>() {
private ProcessorContext processorContext;
@Override
public void init(ProcessorContext context) {
processorContext = context;
}
@Override
public String transform(String value) {
long ts = processorContext.timestamp();
if (ts >= earliest && ts <= latest) {
return value;
}
return null;
}
@Override
public void close() {
}
};
}
}
}
Let me know how it goes.