3

Does pg_repack work for materialized views on postgres v11? I am running into issues installing pg_repack client on my server and hence unable to check myself. As per the documentation it says "pg_repack is a PostgreSQL extension which lets you remove bloat from tables and indexes", so I am assuming it includes materialized views as well.

Laurenz Albe
  • 209,280
  • 17
  • 206
  • 263
nmakb
  • 1,069
  • 1
  • 17
  • 35

1 Answers1

0
DROP TABLE tbt CASCADE;

BEGIN;
CREATE TABLE tbt (
    a int PRIMARY KEY
)
WITH (
    fillfactor = 40,
    autovacuum_enabled = OFF
);
INSERT INTO tbt
SELECT
    g
FROM
    generate_series(1, 2000) g;
CREATE MATERIALIZED VIEW tbtmv AS
SELECT
    *
FROM
    tbt;
CREATE UNIQUE INDEX tbtmv_idx ON tbtmv (a);
COMMIT;

then

--------do the update.
UPDATE
    tbt
SET
    a = a - 10
WHERE
    a < 100;

REFRESH MATERIALIZED VIEW CONCURRENTLY tbtmv;    

SELECT
    *
FROM
    pgstattuple ('tbtmv');

return

table_len          | 73728
tuple_count        | 2000
tuple_len          | 56000
tuple_percent      | 75.95
dead_tuple_count   | 10
dead_tuple_len     | 280
dead_tuple_percent | 0.38
free_space         | 1116
free_percent       | 1.51

 /usr/local/pgsql15/bin/pg_repack -d test15 --table tbtmv

return

ERROR: pg_repack failed with error: ERROR:  relation "tbtmv" does not exist

Then

 /usr/local/pgsql15/bin/pg_repack -d test15 --table tbt

then SELECT * FROM pgstattuple('tbtmv');

-[ RECORD 1 ]------+------
table_len          | 73728
tuple_count        | 2000
tuple_len          | 56000
tuple_percent      | 75.95
dead_tuple_count   | 0
dead_tuple_len     | 0
dead_tuple_percent | 0
free_space         | 1436
free_percent       | 1.95

As you can see dead_tuple_count from 10 to 0. I also tried with delete operation, the result is the same. So does pg_repack work for materialized view? The answer is YES.
Key gotcha is that to make materialized view bloat, you need to use:

REFRESH MATERIALIZED view CONCURRENTLY
jian
  • 4,119
  • 1
  • 17
  • 32
  • Thanks @jian your example shows pg_repack of base table, I want to know if pg_repack can be done on mview. – nmakb Jan 12 '23 at 22:23
  • @nmakb I updated my answer. before repack and after repack, the oid is the same. nothing change, only when you refresh the materialized view. – jian Jan 13 '23 at 07:50
  • my question is can we run pg_repack on an mview? if an mview gets refresh multiple times, it would have bloat. And instead of running vacuum full on mview, can I run pg_repack on the mview? – nmakb Jan 13 '23 at 16:23
  • nice question. I will update later. I found a related post. https://stackoverflow.com/questions/52421411/refreshing-materialized-view-concurrently-causes-table-bloat @nmakb – jian Jan 13 '23 at 16:46