【问题标题】:how can i create materialized view with psycopg2?如何使用 psycopg2 创建物化视图?
【发布时间】:2021-05-24 22:33:37
【问题描述】:

我在使用 postgres 物化视图的 timescaledb 创建连续聚合时遇到错误:

connection = psycopg2.connect(DATABASE_URI)
cursor = connection.cursor()
cursor.execute(
     """CREATE MATERIALIZED VIEW quotes_1h WITH
    (timescaledb.continuous)
    AS
    SELECT ticker, time_bucket('1h', time) as hour,
    min(close) as low,
    max(close) as high,
    first(close, time) as open,
    last(close, time) as close
    FROM quotes
    GROUP BY
    ticker, time_bucket('1h', time);""")
connection.commit()

错误: psycopg2.errors.ActiveSqlTransaction: CREATE MATERIALIZED VIEW ... WITH DATA 不能在事务块内运行

我设置了自动提交,但没有帮助

【问题讨论】:

  • 我无法复制这个。查询字符串也不正确。这部分CREATE MATERIALIZED VIEW quotes_1h WITH.

标签: python postgresql psycopg2 timescaledb


【解决方案1】:

修复它:

from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT
connection.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT)

【讨论】:

  • 截至 2021 年 6 月 22 日的最新 psycopg2、TimescaleDB 和 PostgreSQL 版本对我来说仍然无效
【解决方案2】:

TimescaleDB 目前不支持在同一事务中创建连续聚合并将其具体化。因此有两种选择:

  1. 不要通过将隔离级别设置为 ISOLATION_LEVEL_AUTOCOMMIT 来创建事务,正如另一个回复中所回答的那样。
  2. 不要通过指定 WITH NO DATArefreshing separately 或通过 policy 来实现连续聚合。

第二种情况是:

cursor.execute(
     """CREATE MATERIALIZED VIEW quotes_1h WITH
    (timescaledb.continuous)
    AS
    SELECT ticker, time_bucket('1h', time) as hour,
    min(close) as low,
    max(close) as high,
    first(close, time) as open,
    last(close, time) as close
    FROM quotes
    GROUP BY
    ticker, time_bucket('1h', time)
    WITH NO DATA;""")

【讨论】:

    猜你喜欢
    • 2018-09-13
    • 2018-07-11
    • 2021-05-04
    • 1970-01-01
    • 2010-11-25
    • 2014-04-25
    • 2011-11-22
    • 1970-01-01
    相关资源
    最近更新 更多