简体   繁体   English

如何使用 psycopg2 创建物化视图?

[英]how can i create materialized view with psycopg2?

I'm getting an error on creating continuous aggregates with timescaledb which uses postgres materialized views:我在使用 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()

the error: psycopg2.errors.ActiveSqlTransaction: CREATE MATERIALIZED VIEW... WITH DATA cannot run inside a transaction block错误:psycopg2.errors.ActiveSqlTransaction: CREATE MATERIALIZED VIEW... WITH DATA 不能在事务块内运行

I have set the auto-commit on but it didn't help我已经设置了自动提交,但它没有帮助

fixed it with:修复它:

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

Creating a continuous aggregate and materializing it in the same transaction is currently not supported in TimescaleDB. TimescaleDB 目前不支持在同一事务中创建连续聚合并将其具体化。 Thus there are two choices:因此有两种选择:

  1. Don't create a transaction by setting isolation level to ISOLATION_LEVEL_AUTOCOMMIT as answered in another reply.不要通过将隔离级别设置为ISOLATION_LEVEL_AUTOCOMMIT来创建事务,正如另一个回复中所回答的那样。
  2. Don't materialize the continuous aggregate by specifying WITH NO DATA and refreshing separately or through a policy .不要通过指定WITH NO DATA并单独或通过策略刷新来实现连续聚合。

The second case will be:第二种情况将是:

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;""")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM