JOOQ和TimescaleDB-如何在JOOQ中实现基本的time_bucket语句

时间:2018-11-14 15:05:28

标签: java postgresql kotlin jooq timescaledb

我想在JOOQ中实现一个基本的time_bucket语句。

如果我在控制台中运行此Statement,则可以正常运行:

SELECT time_bucket('5 minutes', time) as t, avg(average)
from TABLE
GROUP BY t

如果我尝试使用JOOQ来实现它,则会出现生成的例程不起作用的问题,因为我无法添加间隔。

我想要类似以下代码的内容,但间隔“ 5分钟”无效:

dslContext.select(timeBucket('5 minutes', TABLE.TIME), avg(TABLE.AVERAGE))
                .from(TABLE)
                .groupBy(timeBucket8('5 minutes', TABLE.TIME))
                .fetch())

是否有一种简单的方法来实现间隔?

1 个答案:

答案 0 :(得分:0)

SQL:

create table mytable (moment timestamp with timezone, ...)
select create_hypertable('mytable', 'moment', chunk_time_interval => INTERVAL '5 minute');

通过jooq选择:

import org.jooq.types.YearToSecond
import java.time.Duration
import org.jooq.impl.DSL.count
import org.jooq.impl.DSL.field

// custom function to combine arguments Duration and OffsetDateTime for TimeBucket2
private fun timeBucket(d: Duration, field: Field<OffsetDateTime>): Field<OffsetDateTime> {
    val f = TimeBucket2()
    f.setBucketWidth(YearToSecond.valueOf(d))
    f.setTs(field)
    return f.asField()
}

// field name alias
val BUCKET = field("bucket", OffsetDateTime::class.java)
val COUNT = field("count", Int::class.java)

val ctx = DSL.using(conn, SQLDialect.POSTGRES, settings)

val recs = ctx.select(
        timeBucket(Duration.ofMinutes(5), MYTABLE.MOMENT).`as`(BUCKET),
        count().`as`(COUNT)
).from(MYTABLE)
        .groupBy(BUCKET)
        .fetch()

for (rec in recs) {
    println(rec[BUCKET] + " => " + rec[COUNT])
}