我编写了一个小程序来从文件导入产品详细信息更新,这比预期的要长得多。(为简洁起见,我将使用精简的示例。)
该程序执行以下操作:
COPY
s 修改后的数据到临时表中。这一切都很好,除了UPDATE
查询需要约 20 秒的时间来处理约 2000 行的小文件。
临时表如下所示:
CREATE TEMPORARY TABLE tmp_products (
product_id integer,
detail text
);
Run Code Online (Sandbox Code Playgroud)
我的更新查询非常简单:
UPDATE products
SET detail = t.detail
FROM tmp_products t
WHERE t.product_id = products.product_id
Run Code Online (Sandbox Code Playgroud)
为了加快速度,我尝试了以下方法,但收效甚微:
在临时表上创建 BTREE 索引。
CREATE INDEX tmp_products_idx
ON tmp_products
USING BTREE
(product_id);
Run Code Online (Sandbox Code Playgroud)
创建哈希索引:
CREATE INDEX tmp_products_idx
ON tmp_products
USING HASH
(product_id);
Run Code Online (Sandbox Code Playgroud)
这两个索引都没有显着改善更新时间。然后我想也许对表进行聚类会有所帮助,但这意味着我不能使用 HASH 索引。所以我修改了程序中的查询以使用 BTREE 索引,然后使用 CLUSTER/ANALYZE:
CREATE INDEX tmp_products_idx
ON tmp_products
USING BTREE
(product_id);
-- Program inserts data …
Run Code Online (Sandbox Code Playgroud)