Custom date range in influx java api

Hey guys writing a task to downsample data in one of my buckets, got it to work using fluxQL but having issues writing the same query using the java api. Can anyone help with explicitly specifying the start and stop range defined in the query below using the java api?
from(bucket: “test-bucket”)

|> range(start: date.truncate(t: -1d, unit: 1d), stop: date.truncate(t: now(), unit: 1d))
|> filter(fn:(r) => r[“_measurement”] == “SAMPLE”)
|> filter(fn:(r) => r[“_field”] == “count”)
|> sum()

Hi @williamxo,

there is no direct suport for using truncate in range, but you can define your custom function:

public static class TruncateDateRange extends AbstractParametrizedFlux {

    public TruncateDateRange(@Nonnull final Flux source) {
        super(source);
        addImport("date");
    }

    @Nonnull
    @Override
    protected String operatorName() {
        return "range";
    }

    @Nonnull
    public TruncateDateRange withRange(@Nonnull final String start,
                                       @Nonnull final String stop,
                                       @Nonnull final String unit) {

        withPropertyValue("start", String.format("date.truncate(t: %s, unit: 1%s)", start, unit));
        withPropertyValue("stop", String.format("date.truncate(t: %s, unit: 1%s)", stop, unit));

        return this;
    }
}
Flux flux = Flux
        .from("telegraf")
        .function(TruncateDateRange.class)
            .withRange("-1d", "now()", "d")
        .filter(Restrictions.measurement().equal("SAMPLE"))
        .filter(Restrictions.field().equal("count"))
        .sum();

System.out.println(flux);

Regards

1 Like

Hi @bednar, Thanks let me try this out

@bednar Works perfect! thanks for your help.

1 Like