【问题标题】:How to implement Parallelism in Postgres如何在 Postgres 中实现并行
【发布时间】:2018-10-25 10:38:21
【问题描述】:

我正在开发基于租户密钥和其他查询条件更新批处理日志的功能。

在我的功能中,我使用连接和循环遍历记录,按顺序更新批处理日志。

我的代码在下面

CREATE TABLE linen_tenant_header
(
    tenant_key character varying(200) NOT NULL,
    tenant_name character varying(50) NOT NULL,
    email character varying(50) NOT NULL,
    created_user character varying(200) NOT NULL,
    updated_user character varying(200),
    created_time timestamp without time zone DEFAULT now(),
    updated_time timestamp without time zone DEFAULT now()
);

CREATE TABLE linen_sc_batch_log
    (
    batch_id serial NOT NULL,
    profile_header_id integer NOT NULL,
    batch_status character varying(200),
    batch_type character varying(200) NOT NULL,
    batch_mode character varying(200) NOT NULL,
    tenant_key character varying(200) NOT NULL,
    created_user character varying(200),
    updated_user character varying(200),
    created_time timestamp without time zone DEFAULT now(),
    updated_time timestamp without time zone DEFAULT now(),
);

CREATE TABLE linen_sc_expressions
(
    expression_id integer NOT NULL,
    reference_id integer NOT NULL,
    tenant_key character varying(200) NOT NULL,
    expression_text character varying(10000) NOT NULL,
    start_date date NOT NULL,
    end_date date,
    created_user character varying(200) NOT NULL,
    updated_user character varying(200),
    created_time timestamp without time zone DEFAULT now(),
    updated_time timestamp without time zone DEFAULT now()
);

CREATE OR REPLACE FUNCTION sample_function(
    tenant_key TEXT
) RETURNS VOID AS $$
DECLARE
    rec RECORD;
BEGIN
    FOR rec IN SELECT * FROM linen_sc_batch_log bl, linen_sc_expressions sce  where bl.profile_header_id = sce.reference_id and bl.tenant_key = $1 and sce.tenant_key = $1
    LOOP
        EXECUTE FORMAT('UPDATE linen_sc_batch_log set batch_status = %L where tenant_key = %L and batch_id = %L::INTEGER', 'EXTRACTED', tenant_key, rec.batch_id);
    END LOOP;
END;
$$ LANGUAGE plpgsql;

我的功能可以正常工作,但我需要通过添加并行性来增强我的功能。

我想同时并行更新所有记录,而不是循环遍历所有记录。

我研究了 google 和 PostgreSQL 的文章,但没有找到相关的概念。

【问题讨论】:

    标签: sql postgresql postgresql-10 postgresql-11


    【解决方案1】:

    我认为这可以在一条 SQL 语句中完成:

    UPDATE linen_sc_batch_log AS bl
    SET batch_status = 'EXTRACTED'
    FROM linen_sc_expressions AS sce
    WHERE bl.profile_header_id = sce.reference_id
      AND bl.tenant_key = $1 AND sce.tenant_key = $1;
    

    如果您想要并行化,您可以在并发数据库连接上运行多个此类更新,为每个更新添加一个类似AND id % 10 = <em>n</em> 的子句。

    【讨论】:

    • yaa 我们可以做到,但在嵌套循环和复杂功能或数百万条记录的情况下,它需要非常多的时间,所以我们需要并行性。所以对于示例功能,我已经发布了问题。请问这个问题需要并行实现
    • 我添加了一些东西。
    猜你喜欢
    • 1970-01-01
    • 2012-02-08
    • 1970-01-01
    • 1970-01-01
    • 2018-05-30
    • 2021-11-14
    • 1970-01-01
    • 1970-01-01
    • 2013-09-18
    相关资源
    最近更新 更多