Skip to content

Openverse is a search engine for openly-licensed media. This monorepo includes all application code.

Drop and recreate matview in data refresh (#2006)

Staci Mullinsdb3986ba5d38
diff --git a/catalog/dags/common/popularity/sql.py b/catalog/dags/common/popularity/sql.py
index 752620951..75a8228fa 100644
--- a/catalog/dags/common/popularity/sql.py
+++ b/catalog/dags/common/popularity/sql.py
@@ -68,6 +68,21 @@ POPULARITY_METRICS_TABLE_COLUMNS = [
]
+def drop_media_matview(
+ postgres_conn_id: str,
+ media_type: str = IMAGE,
+ db_view: str = IMAGE_VIEW_NAME,
+ pg_timeout: float = timedelta(minutes=10).total_seconds(),
+):
+ if media_type == AUDIO:
+ db_view = AUDIO_VIEW_NAME
+
+ postgres = PostgresHook(
+ postgres_conn_id=postgres_conn_id, default_statement_timeout=pg_timeout
+ )
+ postgres.run(f"DROP MATERIALIZED VIEW IF EXISTS public.{db_view} CASCADE;")
+
+
def drop_media_popularity_relations(
postgres_conn_id,
media_type=IMAGE,
diff --git a/catalog/dags/data_refresh/dag_factory.py b/catalog/dags/data_refresh/dag_factory.py
index 385998354..f662e32ff 100644
--- a/catalog/dags/data_refresh/dag_factory.py
+++ b/catalog/dags/data_refresh/dag_factory.py
@@ -51,6 +51,11 @@ from common.constants import (
from common.sql import PGExecuteQueryOperator
from data_refresh.data_refresh_task_factory import create_data_refresh_task_group
from data_refresh.data_refresh_types import DATA_REFRESH_CONFIGS, DataRefresh
+from data_refresh.recreate_view_data_task_factory import DROP_DB_VIEW_TASK_ID
+from data_refresh.recreate_view_data_task_factory import (
+ GROUP_ID as RECREATE_MATVIEW_GROUP_ID,
+)
+from data_refresh.recreate_view_data_task_factory import create_recreate_view_data_task
from data_refresh.refresh_popularity_metrics_task_factory import (
GROUP_ID as REFRESH_POPULARITY_METRICS_GROUP_ID,
)
@@ -58,16 +63,15 @@ from data_refresh.refresh_popularity_metrics_task_factory import (
UPDATE_MEDIA_POPULARITY_METRICS_TASK_ID,
create_refresh_popularity_metrics_task_group,
)
-from data_refresh.refresh_view_data_task_factory import (
- UPDATE_DB_VIEW_TASK_ID,
- create_refresh_view_data_task,
-)
from data_refresh.reporting import report_record_difference, report_status
logger = logging.getLogger(__name__)
-REFRESH_MATERIALIZED_VIEW_TASK_ID = UPDATE_DB_VIEW_TASK_ID
+# The first task in the recreate_matview TaskGroup
+RECREATE_MATERIALIZED_VIEW_TASK_ID = (
+ f"{RECREATE_MATVIEW_GROUP_ID}.{DROP_DB_VIEW_TASK_ID}"
+)
# The first task in the refresh_popularity_metrics TaskGroup
REFRESH_POPULARITY_METRICS_TASK_ID = (
f"{REFRESH_POPULARITY_METRICS_GROUP_ID}"
@@ -110,7 +114,7 @@ def _month_check(dag_id: str, session: SASession = None) -> str:
return (
REFRESH_POPULARITY_METRICS_TASK_ID
if force_refresh_metrics
- else REFRESH_MATERIALIZED_VIEW_TASK_ID
+ else RECREATE_MATERIALIZED_VIEW_TASK_ID
)
# Get the most recent successful dagrun for this Dag
@@ -135,7 +139,7 @@ def _month_check(dag_id: str, session: SASession = None) -> str:
return (
REFRESH_POPULARITY_METRICS_TASK_ID
if not is_last_dagrun_in_current_month
- else REFRESH_MATERIALIZED_VIEW_TASK_ID
+ else RECREATE_MATERIALIZED_VIEW_TASK_ID
)
@@ -148,7 +152,7 @@ def _month_check_with_reporting(dag_id: str, media_type: str) -> str:
next_task_id = _month_check(dag_id)
next_step = {
REFRESH_POPULARITY_METRICS_TASK_ID: "update popularity metrics",
- REFRESH_MATERIALIZED_VIEW_TASK_ID: "refresh matview",
+ RECREATE_MATERIALIZED_VIEW_TASK_ID: "recreate matview",
}.get(next_task_id, "unable to determine next step")
message = f":horse_racing: Starting data refresh | _Next: {next_step}_"
report_status(media_type, message, dag_id)
@@ -228,9 +232,10 @@ def create_data_refresh_dag(data_refresh: DataRefresh, external_dag_ids: Sequenc
data_refresh
)
- # Refresh the materialized view. This occurs on all DagRuns and updates
- # popularity data for newly ingested records.
- refresh_matview = create_refresh_view_data_task(data_refresh)
+ # Drop and recreate the materialized view. This occurs on all DagRuns and
+ # updates popularity data for newly ingested records. Formerly, we would refresh
+ # the materialized view, but that process would consistently time out.
+ recreate_matview = create_recreate_view_data_task(data_refresh)
# Trigger the actual data refresh on the remote data refresh server, and wait
# for it to complete.
@@ -283,9 +288,9 @@ def create_data_refresh_dag(data_refresh: DataRefresh, external_dag_ids: Sequenc
)
# Set up task dependencies
- month_check >> [refresh_popularity_metrics, refresh_matview]
+ month_check >> [refresh_popularity_metrics, recreate_matview]
before_record_count >> data_refresh_group
- refresh_popularity_metrics >> refresh_matview >> data_refresh_group
+ refresh_popularity_metrics >> recreate_matview >> data_refresh_group
data_refresh_group >> after_record_count >> report_counts
data_refresh_group >> trigger_filtered_index_creation
diff --git a/catalog/dags/data_refresh/recreate_view_data_task_factory.py b/catalog/dags/data_refresh/recreate_view_data_task_factory.py
new file mode 100644
index 000000000..21834ed4f
--- /dev/null
+++ b/catalog/dags/data_refresh/recreate_view_data_task_factory.py
@@ -0,0 +1,81 @@
+"""
+# Recreate Materialized View Task Factory
+This file generates a TaskGroup that recreates the materialized view for a
+given media type, using a factory function.
+
+The task drops and recreates the materialized view, but not the underlying tables. This
+means that the only effect is to add or update data (including popularity data)
+for records which have been ingested since the last time the view was
+refreshed.
+
+This should be run every time before a data refresh is triggered.
+"""
+from airflow.operators.python import PythonOperator
+from airflow.utils.task_group import TaskGroup
+from airflow.utils.trigger_rule import TriggerRule
+
+from common.constants import POSTGRES_CONN_ID
+from common.popularity import sql
+from data_refresh import reporting
+from data_refresh.data_refresh_types import DataRefresh
+
+
+GROUP_ID = "recreate_matview"
+DROP_DB_VIEW_TASK_ID = "drop_materialized_popularity_view"
+CREATE_DB_VIEW_TASK_ID = "create_materialized_popularity_view"
+
+
+def create_recreate_view_data_task(data_refresh: DataRefresh):
+ """
+ Create the recreate related tasks.
+
+ The task drops and recreates the materialized view for the given media type. The
+ view collates popularity data for each record. Recreating has the effect of adding
+ popularity data for records that were ingested since the last time the view was
+ created or refreshed, and updating popularity data for existing records. It also
+ creates a reporting task which will report the status of the matview refresh once
+ it is complete.
+
+ The view is dropped and recreated rather than refreshed, because refreshing the view
+ takes much longer in production and times out.
+
+ Required Arguments:
+
+ data_refresh: configuration information for the data refresh
+ """
+ with TaskGroup(group_id=GROUP_ID) as recreate_matview:
+ drop_matview = PythonOperator(
+ task_id=DROP_DB_VIEW_TASK_ID,
+ python_callable=sql.drop_media_matview,
+ op_kwargs={
+ "postgres_conn_id": POSTGRES_CONN_ID,
+ "media_type": data_refresh.media_type,
+ },
+ trigger_rule=TriggerRule.NONE_FAILED_MIN_ONE_SUCCESS,
+ retries=0,
+ )
+ create_matview = PythonOperator(
+ task_id=CREATE_DB_VIEW_TASK_ID,
+ python_callable=sql.create_media_view,
+ op_kwargs={
+ "postgres_conn_id": POSTGRES_CONN_ID,
+ "media_type": data_refresh.media_type,
+ },
+ execution_timeout=data_refresh.create_materialized_view_timeout,
+ retries=0,
+ doc_md=create_recreate_view_data_task.__doc__,
+ )
+ recreate_status = PythonOperator(
+ task_id=f"report_{GROUP_ID}_status",
+ python_callable=reporting.report_status,
+ op_kwargs={
+ "media_type": data_refresh.media_type,
+ "dag_id": data_refresh.dag_id,
+ "message": "Matview refresh complete | "
+ "_Next: ingestion server data refresh_",
+ },
+ )
+
+ drop_matview >> create_matview >> recreate_status
+
+ return recreate_matview
diff --git a/catalog/dags/data_refresh/refresh_view_data_task_factory.py b/catalog/dags/data_refresh/refresh_view_data_task_factory.py
deleted file mode 100644
index 69fc4a07c..000000000
--- a/catalog/dags/data_refresh/refresh_view_data_task_factory.py
+++ /dev/null
@@ -1,65 +0,0 @@
-"""
-# Refresh Materialized View Task Factory
-This file generates a Task that refreshes the materialized view for a
-given media type, using a factory function.
-
-The task refreshes the materialized view, but not the underlying tables. This
-means that the only effect is to add or update data (including popularity data)
-for records which have been ingested since the last time the view was
-refreshed.
-
-This should be run every time before a data refresh is triggered.
-"""
-from airflow.operators.python import PythonOperator
-from airflow.utils.trigger_rule import TriggerRule
-
-from common.constants import POSTGRES_CONN_ID
-from common.popularity import sql
-from data_refresh import reporting
-from data_refresh.data_refresh_types import DataRefresh
-
-
-UPDATE_DB_VIEW_TASK_ID = "update_materialized_popularity_view"
-
-
-def create_refresh_view_data_task(data_refresh: DataRefresh):
- """
- Create the refresh related tasks.
-
- The task refreshes the materialized view for the given media type. The view collates
- popularity data for each record. Refreshing has the effect of adding popularity data
- for records that were ingested since the last time the view was refreshed, and
- updating popularity data for existing records. It also creates a reporting task
- which will report the status of the matview refresh once it is complete.
-
- Required Arguments:
-
- data_refresh: configuration information for the data refresh
- """
- refresh_matview = PythonOperator(
- task_id=UPDATE_DB_VIEW_TASK_ID,
- python_callable=sql.update_db_view,
- op_kwargs={
- "postgres_conn_id": POSTGRES_CONN_ID,
- "media_type": data_refresh.media_type,
- },
- execution_timeout=data_refresh.refresh_matview_timeout,
- trigger_rule=TriggerRule.NONE_FAILED_MIN_ONE_SUCCESS,
- retries=0,
- doc_md=create_refresh_view_data_task.__doc__,
- )
-
- refresh_status = PythonOperator(
- task_id=f"report_{UPDATE_DB_VIEW_TASK_ID}_status",
- python_callable=reporting.report_status,
- op_kwargs={
- "media_type": data_refresh.media_type,
- "dag_id": data_refresh.dag_id,
- "message": "Matview refresh complete | "
- "_Next: ingestion server data refresh_",
- },
- )
-
- refresh_matview >> refresh_status
-
- return refresh_matview
diff --git a/catalog/tests/dags/data_refresh/test_dag_factory.py b/catalog/tests/dags/data_refresh/test_dag_factory.py
index fa5d31c68..6a299fa78 100644
--- a/catalog/tests/dags/data_refresh/test_dag_factory.py
+++ b/catalog/tests/dags/data_refresh/test_dag_factory.py
@@ -10,7 +10,7 @@ from airflow.utils.types import DagRunType
from data_refresh import dag_factory
from data_refresh.dag_factory import (
- REFRESH_MATERIALIZED_VIEW_TASK_ID,
+ RECREATE_MATERIALIZED_VIEW_TASK_ID,
REFRESH_POPULARITY_METRICS_TASK_ID,
)
@@ -44,7 +44,7 @@ def _create_dagrun(start_date, dag_state, conf={}):
None,
datetime(2022, 3, 1, 0, 0, 0),
datetime(2022, 3, 2, 0, 0, 0),
- REFRESH_MATERIALIZED_VIEW_TASK_ID,
+ RECREATE_MATERIALIZED_VIEW_TASK_ID,
),
# Last dagrun was in the same month, different year
(
@@ -81,14 +81,14 @@ def _create_dagrun(start_date, dag_state, conf={}):
False,
datetime(2022, 3, 1, 0, 0, 0),
datetime(2022, 3, 2, 0, 0, 0),
- REFRESH_MATERIALIZED_VIEW_TASK_ID,
+ RECREATE_MATERIALIZED_VIEW_TASK_ID,
),
# Last dagrun was in a previous month
(
False,
datetime(2022, 2, 1, 0, 0, 0),
datetime(2022, 3, 2, 0, 0, 0),
- REFRESH_MATERIALIZED_VIEW_TASK_ID,
+ RECREATE_MATERIALIZED_VIEW_TASK_ID,
),
],
)
@@ -126,7 +126,7 @@ def test_month_check_ignores_failed_dagruns():
"task_id, expected_message",
[
(REFRESH_POPULARITY_METRICS_TASK_ID, "update popularity metrics"),
- (REFRESH_MATERIALIZED_VIEW_TASK_ID, "refresh matview"),
+ (RECREATE_MATERIALIZED_VIEW_TASK_ID, "recreate matview"),
("Some other task ID", "unable to determine next step"),
],
)