Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

refresh materialized view periodically postgres

for optimization purposes I'm using a materialized view, to refresh it periodically I have set a cron job that runs each period t in my case every three hours. my questions are:

  1. what's the best way to refresh a materialized view?
  2. what can go wrong if using a cron job to refresh a materialized view?

I have come across a postgres plugin that schedule jobs link

like image 945
rachid el kedmiri Avatar asked Oct 30 '17 10:10

rachid el kedmiri


People also ask

How do I schedule a materialized view to refresh?

To schedule a refresh for the materialized view, next to Repeats, select the Time Interval: Daily, Weekly, or Monthly. From the Select days menu, select Every weekday, or Every day. Specify the hour of the day.

Can materialized view be updated automatically?

Amazon Redshift can automatically refresh materialized views with up-to-date data from its base tables when materialized views are created with or altered to have the autorefresh option. Amazon Redshift autorefreshes materialized views as soon as possible after base tables changes.

How materialized view refresh works in postgresql?

Parameters. Refresh the materialized view without locking out concurrent selects on the materialized view. Without this option a refresh which affects a lot of rows will tend to use fewer resources and complete more quickly, but could block other connections which are trying to read from the materialized view.

How long does it take to refresh a materialized view Postgres?

Scheduling the REFRESH operation And then your materialized view will be refreshed at each 30 minutes.


2 Answers

the best way is to execute periodically a script that does the task:

the script is:

#!/bin/sh
psql -U user_name -d database_instance_name -c 'refresh materialized view view_name'

and add an entry in the crontab like:

@hourly  /full_path/script_name.sh
like image 88
rachid el kedmiri Avatar answered Sep 22 '22 16:09

rachid el kedmiri


Also pg_cron extension can do job for Linux installation. Here is a example that i use, refreshing every 5 minute;

INSERT INTO cron.job (schedule, command, nodename, nodeport, database, username)
VALUES ('*/5 * * * *', 'REFRESH MATERIALIZED VIEW public.mv_anyquery', 
'127.0.0.1', 5432, 'geodb', 'postgres');

nodename(127.0.0.1) may be necessary trust authentication in pg_hba.conf.

like image 27
Barış Serkan AKIN Avatar answered Sep 21 '22 16:09

Barış Serkan AKIN