Skip to content

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

Remove popularity constants view (#2883)

Staci Mullinsce14b26eed06
diff --git a/catalog/dags/common/popularity/constants.py b/catalog/dags/common/popularity/constants.py
index 6742027eb..c2588840e 100644
--- a/catalog/dags/common/popularity/constants.py
+++ b/catalog/dags/common/popularity/constants.py
@@ -1,8 +1,6 @@
IMAGE_VIEW_NAME = "image_view"
AUDIO_VIEW_NAME = "audio_view"
AUDIOSET_VIEW_NAME = "audioset_view"
-IMAGE_POPULARITY_CONSTANTS_VIEW = "image_popularity_constants"
-AUDIO_POPULARITY_CONSTANTS_VIEW = "audio_popularity_constants"
IMAGE_POPULARITY_PERCENTILE_FUNCTION = "image_popularity_percentile"
AUDIO_POPULARITY_PERCENTILE_FUNCTION = "audio_popularity_percentile"
STANDARDIZED_IMAGE_POPULARITY_FUNCTION = "standardized_image_popularity"
diff --git a/catalog/dags/common/popularity/sql.py b/catalog/dags/common/popularity/sql.py
index 996817c47..939a9f65f 100644
--- a/catalog/dags/common/popularity/sql.py
+++ b/catalog/dags/common/popularity/sql.py
@@ -2,36 +2,33 @@ from collections import namedtuple
from datetime import timedelta
from textwrap import dedent
+from airflow.decorators import task, task_group
from airflow.models.abstractoperator import AbstractOperator
-from common.constants import AUDIO, IMAGE
+from common.constants import AUDIO, DAG_DEFAULT_ARGS, IMAGE
from common.loader.sql import TABLE_NAMES
from common.popularity.constants import (
- AUDIO_POPULARITY_CONSTANTS_VIEW,
AUDIO_POPULARITY_PERCENTILE_FUNCTION,
AUDIO_VIEW_NAME,
- IMAGE_POPULARITY_CONSTANTS_VIEW,
IMAGE_POPULARITY_PERCENTILE_FUNCTION,
IMAGE_VIEW_NAME,
STANDARDIZED_AUDIO_POPULARITY_FUNCTION,
STANDARDIZED_IMAGE_POPULARITY_FUNCTION,
)
-from common.sql import PostgresHook
+from common.sql import PostgresHook, _single_value
from common.storage import columns as col
from common.storage.db_columns import AUDIO_TABLE_COLUMNS, IMAGE_TABLE_COLUMNS
DEFAULT_PERCENTILE = 0.85
-
-IMAGE_POP_CONSTANTS_IDX = "image_popularity_constants_provider_metric_idx"
-AUDIO_POP_CONSTANTS_IDX = "audio_popularity_constants_provider_metric_idx"
IMAGE_VIEW_ID_IDX = "image_view_identifier_idx"
AUDIO_VIEW_ID_IDX = "audio_view_identifier_idx"
IMAGE_VIEW_PROVIDER_FID_IDX = "image_view_provider_fid_idx"
AUDIO_VIEW_PROVIDER_FID_IDX = "audio_view_provider_fid_idx"
# Column name constants
+VALUE = "val"
CONSTANT = "constant"
FID = col.FOREIGN_ID.db_name
IDENTIFIER = col.IDENTIFIER.db_name
@@ -64,8 +61,17 @@ POPULARITY_METRICS_TABLE_COLUMNS = [
Column(name=PARTITION, definition="character varying(80) PRIMARY KEY"),
Column(name=METRIC, definition="character varying(80)"),
Column(name=PERCENTILE, definition="float"),
+ Column(name=VALUE, definition="float"),
+ Column(name=CONSTANT, definition="float"),
]
+# Further refactoring of this nature will be done in
+# https://github.com/WordPress/openverse/issues/2678.
+POPULARITY_METRICS_BY_MEDIA_TYPE = {
+ AUDIO: AUDIO_POPULARITY_METRICS,
+ IMAGE: IMAGE_POPULARITY_METRICS,
+}
+
def drop_media_matview(
postgres_conn_id: str,
@@ -86,25 +92,19 @@ def drop_media_popularity_relations(
postgres_conn_id,
media_type=IMAGE,
db_view=IMAGE_VIEW_NAME,
- constants=IMAGE_POPULARITY_CONSTANTS_VIEW,
metrics=IMAGE_POPULARITY_METRICS_TABLE_NAME,
pg_timeout: float = timedelta(minutes=10).total_seconds(),
):
if media_type == AUDIO:
db_view = AUDIO_VIEW_NAME
- constants = AUDIO_POPULARITY_CONSTANTS_VIEW
metrics = AUDIO_POPULARITY_METRICS_TABLE_NAME
postgres = PostgresHook(
postgres_conn_id=postgres_conn_id, default_statement_timeout=pg_timeout
)
drop_media_view = f"DROP MATERIALIZED VIEW IF EXISTS public.{db_view} CASCADE;"
- drop_popularity_constants = (
- f"DROP MATERIALIZED VIEW IF EXISTS public.{constants} CASCADE;"
- )
drop_popularity_metrics = f"DROP TABLE IF EXISTS public.{metrics} CASCADE;"
postgres.run(drop_media_view)
- postgres.run(drop_popularity_constants)
postgres.run(drop_popularity_metrics)
@@ -153,27 +153,34 @@ def create_media_popularity_metrics(
postgres.run(query)
+@task
def update_media_popularity_metrics(
postgres_conn_id,
media_type=IMAGE,
popularity_metrics=None,
popularity_metrics_table=IMAGE_POPULARITY_METRICS_TABLE_NAME,
+ popularity_percentile=IMAGE_POPULARITY_PERCENTILE_FUNCTION,
task: AbstractOperator = None,
):
if popularity_metrics is None:
- if media_type == AUDIO:
- popularity_metrics = AUDIO_POPULARITY_METRICS
- else:
- popularity_metrics = IMAGE_POPULARITY_METRICS
+ popularity_metrics = POPULARITY_METRICS_BY_MEDIA_TYPE[media_type]
if media_type == AUDIO:
popularity_metrics_table = AUDIO_POPULARITY_METRICS_TABLE_NAME
postgres = PostgresHook(
postgres_conn_id=postgres_conn_id,
default_statement_timeout=PostgresHook.get_execution_timeout(task),
)
+
column_names = [c.name for c in POPULARITY_METRICS_TABLE_COLUMNS]
+
+ # Note that we do not update the val and constant. That is only done during the
+ # calculation tasks. In other words, we never want to clear out the current value of
+ # the popularity constant unless we're already done calculating the new one, since
+ # that can be a time consuming process.
updates_string = ",\n ".join(
- f"{c}=EXCLUDED.{c}" for c in column_names if c != PARTITION
+ f"{c}=EXCLUDED.{c}"
+ for c in column_names
+ if c not in [PARTITION, CONSTANT, VALUE]
)
popularity_metric_inserts = _get_popularity_metric_insert_values_string(
popularity_metrics
@@ -191,7 +198,117 @@ def update_media_popularity_metrics(
;
"""
)
- postgres.run(query)
+ return postgres.run(query)
+
+
+@task
+def calculate_media_popularity_percentile_value(
+ postgres_conn_id,
+ provider,
+ media_type=IMAGE,
+ popularity_metrics_table=IMAGE_POPULARITY_METRICS_TABLE_NAME,
+ popularity_percentile=IMAGE_POPULARITY_PERCENTILE_FUNCTION,
+ task: AbstractOperator = None,
+):
+ if media_type == AUDIO:
+ popularity_metrics_table = AUDIO_POPULARITY_METRICS_TABLE_NAME
+ popularity_percentile = AUDIO_POPULARITY_PERCENTILE_FUNCTION
+
+ postgres = PostgresHook(
+ postgres_conn_id=postgres_conn_id,
+ default_statement_timeout=PostgresHook.get_execution_timeout(task),
+ )
+
+ # Calculate the percentile value. E.g. if `percentile` = 0.80, then we'll
+ # calculate the _value_ of the 80th percentile for this provider's
+ # popularity metric.
+ calculate_new_percentile_value_query = dedent(
+ f"""
+ SELECT {popularity_percentile}({PARTITION}, {METRIC}, {PERCENTILE})
+ FROM {popularity_metrics_table}
+ WHERE {col.PROVIDER.db_name}='{provider}';
+ """
+ )
+
+ return postgres.run(calculate_new_percentile_value_query, handler=_single_value)
+
+
+@task
+def update_percentile_and_constants_values_for_provider(
+ postgres_conn_id,
+ provider,
+ raw_percentile_value,
+ media_type=IMAGE,
+ popularity_metrics=None,
+ popularity_metrics_table=IMAGE_POPULARITY_METRICS_TABLE_NAME,
+ task: AbstractOperator = None,
+):
+ if popularity_metrics is None:
+ popularity_metrics = POPULARITY_METRICS_BY_MEDIA_TYPE.get(media_type, {})
+ if media_type == AUDIO:
+ popularity_metrics_table = AUDIO_POPULARITY_METRICS_TABLE_NAME
+
+ if raw_percentile_value is None:
+ # Occurs when a provider has a metric configured, but there are no records
+ # with any data for that metric.
+ return
+
+ postgres = PostgresHook(
+ postgres_conn_id=postgres_conn_id,
+ default_statement_timeout=PostgresHook.get_execution_timeout(task),
+ )
+
+ provider_info = popularity_metrics.get(provider)
+ percentile = provider_info.get("percentile", DEFAULT_PERCENTILE)
+
+ # Calculate the popularity constant using the percentile value
+ percentile_value = raw_percentile_value or 1
+ new_constant = ((1 - percentile) / (percentile)) * percentile_value
+
+ # Update the percentile value and constant in the metrics table
+ update_constant_query = dedent(
+ f"""
+ UPDATE public.{popularity_metrics_table}
+ SET {VALUE} = {percentile_value}, {CONSTANT} = {new_constant}
+ WHERE {col.PROVIDER.db_name} = '{provider}';
+ """
+ )
+ return postgres.run(update_constant_query)
+
+
+@task_group
+def update_percentile_and_constants_for_provider(
+ postgres_conn_id, provider, media_type=IMAGE, execution_timeout=None
+):
+ calculate_percentile_val = calculate_media_popularity_percentile_value.override(
+ task_id="calculate_percentile_value",
+ execution_timeout=execution_timeout
+ or DAG_DEFAULT_ARGS.get("execution_timeout"),
+ )(
+ postgres_conn_id=postgres_conn_id,
+ provider=provider,
+ media_type=media_type,
+ )
+ calculate_percentile_val.doc = (
+ "Calculate the percentile popularity value for this provider. For"
+ " example, if this provider has `percentile`=0.80 and `metric`='views',"
+ " calculate the 80th percentile value of views for all records for this"
+ " provider."
+ )
+
+ update_metrics_table = update_percentile_and_constants_values_for_provider.override(
+ task_id="update_percentile_values_and_constant",
+ )(
+ postgres_conn_id=postgres_conn_id,
+ provider=provider,
+ raw_percentile_value=calculate_percentile_val,
+ media_type=media_type,
+ )
+ update_metrics_table.doc = (
+ "Given the newly calculated percentile value, calculate the"
+ " popularity constant and update the metrics table with the newly"
+ " calculated values."
+ )
def _get_popularity_metric_insert_values_string(
@@ -213,7 +330,8 @@ def _format_popularity_metric_insert_tuple_string(
metric,
percentile,
):
- return f"('{provider}', '{metric}', {percentile})"
+ # Default null val and constant
+ return f"('{provider}', '{metric}', {percentile}, null, null)"
def create_media_popularity_percentile_function(
@@ -246,85 +364,14 @@ def create_media_popularity_percentile_function(
postgres.run(query)
-def create_media_popularity_constants_view(
- postgres_conn_id,
- media_type=IMAGE,
- popularity_constants=IMAGE_POPULARITY_CONSTANTS_VIEW,
- popularity_constants_idx=IMAGE_POP_CONSTANTS_IDX,
- popularity_metrics=IMAGE_POPULARITY_METRICS_TABLE_NAME,
- popularity_percentile=IMAGE_POPULARITY_PERCENTILE_FUNCTION,
- task: AbstractOperator = None,
-):
- postgres = PostgresHook(
- postgres_conn_id=postgres_conn_id,
- default_statement_timeout=PostgresHook.get_execution_timeout(task),
- )
- if media_type == AUDIO:
- popularity_constants = AUDIO_POPULARITY_CONSTANTS_VIEW
- popularity_constants_idx = AUDIO_POP_CONSTANTS_IDX
- popularity_metrics = AUDIO_POPULARITY_METRICS_TABLE_NAME
- popularity_percentile = AUDIO_POPULARITY_PERCENTILE_FUNCTION
-
- create_view_query = dedent(
- f"""
- CREATE MATERIALIZED VIEW public.{popularity_constants} AS
- WITH
- popularity_metric_raw_values AS (
- SELECT
- *,
- {popularity_percentile}({PARTITION}, {METRIC}, {PERCENTILE})
- AS raw_value
- FROM {popularity_metrics}
- ),
- popularity_metric_values AS(
- SELECT
- *,
- CASE
- WHEN raw_value=0 THEN
- 1
- ELSE
- raw_value
- END AS value
- FROM popularity_metric_raw_values
- )
- SELECT *, ((1 - {PERCENTILE}) / {PERCENTILE}) * value AS {CONSTANT}
- FROM popularity_metric_values;
- """
- )
- add_idx_query = dedent(
- f"""
- CREATE UNIQUE INDEX {popularity_constants_idx}
- ON public.{popularity_constants}
- USING btree({PARTITION}, {METRIC});
- """
- )
- postgres.run(create_view_query)
- postgres.run(add_idx_query)
-
-
-def update_media_popularity_constants(
- postgres_conn_id,
- media_type=IMAGE,
- popularity_constants_view=IMAGE_POPULARITY_CONSTANTS_VIEW,
- task: AbstractOperator = None,
-):
- if media_type == AUDIO:
- popularity_constants_view = AUDIO_POPULARITY_CONSTANTS_VIEW
- postgres = PostgresHook(
- postgres_conn_id=postgres_conn_id,
- default_statement_timeout=PostgresHook.get_execution_timeout(task),
- )
- postgres.run(f"REFRESH MATERIALIZED VIEW CONCURRENTLY {popularity_constants_view};")
-
-
def create_standardized_media_popularity_function(
postgres_conn_id,
media_type=IMAGE,
function_name=STANDARDIZED_IMAGE_POPULARITY_FUNCTION,
- popularity_constants=IMAGE_POPULARITY_CONSTANTS_VIEW,
+ popularity_metrics=IMAGE_POPULARITY_METRICS_TABLE_NAME,
):
if media_type == AUDIO:
- popularity_constants = AUDIO_POPULARITY_CONSTANTS_VIEW
+ popularity_metrics = AUDIO_POPULARITY_METRICS_TABLE_NAME
function_name = STANDARDIZED_AUDIO_POPULARITY_FUNCTION
postgres = PostgresHook(
postgres_conn_id=postgres_conn_id, default_statement_timeout=10.0
@@ -335,7 +382,7 @@ def create_standardized_media_popularity_function(
provider text, meta_data jsonb
) RETURNS FLOAT AS $$
SELECT ($2->>{METRIC})::float / (($2->>{METRIC})::float + {CONSTANT})
- FROM {popularity_constants} WHERE provider=$1;
+ FROM {popularity_metrics} WHERE provider=$1;
$$
LANGUAGE SQL
STABLE
@@ -403,7 +450,7 @@ def create_media_view(
def get_providers_with_popularity_data_for_media_type(
postgres_conn_id: str,
media_type: str = IMAGE,
- constants_view: str = IMAGE_POPULARITY_CONSTANTS_VIEW,
+ popularity_metrics: str = IMAGE_POPULARITY_METRICS_TABLE_NAME,
pg_timeout: float = timedelta(minutes=10).total_seconds(),
):
"""
@@ -411,13 +458,13 @@ def get_providers_with_popularity_data_for_media_type(
for the given media type.
"""
if media_type == AUDIO:
- constants_view = AUDIO_POPULARITY_CONSTANTS_VIEW
+ popularity_metrics = AUDIO_POPULARITY_METRICS_TABLE_NAME
postgres = PostgresHook(
postgres_conn_id=postgres_conn_id, default_statement_timeout=pg_timeout
)
providers = postgres.get_records(
- f"SELECT DISTINCT provider FROM public.{constants_view};"
+ f"SELECT DISTINCT provider FROM public.{popularity_metrics};"
)
return [x[0] for x in providers]
diff --git a/catalog/dags/common/sql.py b/catalog/dags/common/sql.py
index f0d367e89..15e794009 100644
--- a/catalog/dags/common/sql.py
+++ b/catalog/dags/common/sql.py
@@ -27,6 +27,14 @@ logger = logging.getLogger(__name__)
# https://airflow.apache.org/docs/apache-airflow-providers-postgres/stable/_api/airflow/providers/postgres/hooks/postgres/index.html#airflow.providers.postgres.hooks.postgres.PostgresHook.copy_expert # noqa
+def _single_value(cursor):
+ try:
+ row = cursor.fetchone()
+ return row[0]
+ except Exception as e:
+ raise ValueError("Unable to extract expected row data from cursor") from e
+
+
class PostgresHook(UpstreamPostgresHook):
"""
PostgresHook that sets the database timeout on any query to match the airflow task
diff --git a/catalog/dags/data_refresh/dag_factory.py b/catalog/dags/data_refresh/dag_factory.py
index c7e16fb81..de8291d6a 100644
--- a/catalog/dags/data_refresh/dag_factory.py
+++ b/catalog/dags/data_refresh/dag_factory.py
@@ -34,7 +34,7 @@ from common.constants import (
OPENLEDGER_API_CONN_ID,
XCOM_PULL_TEMPLATE,
)
-from common.sql import PGExecuteQueryOperator
+from common.sql import PGExecuteQueryOperator, _single_value
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.reporting import report_record_difference
@@ -43,14 +43,6 @@ from data_refresh.reporting import report_record_difference
logger = logging.getLogger(__name__)
-def _single_value(cursor):
- try:
- row = cursor.fetchone()
- return row[0]
- except Exception as e:
- raise ValueError("Unable to extract expected row data from cursor") from e
-
-
def create_data_refresh_dag(data_refresh: DataRefresh, external_dag_ids: Sequence[str]):
"""
Instantiate a DAG for a data refresh.
diff --git a/catalog/dags/database/batched_update/batched_update.py b/catalog/dags/database/batched_update/batched_update.py
index 4d644ee09..74c2f7893 100644
--- a/catalog/dags/database/batched_update/batched_update.py
+++ b/catalog/dags/database/batched_update/batched_update.py
@@ -7,21 +7,13 @@ from airflow.models.abstractoperator import AbstractOperator
from common import slack
from common.constants import POSTGRES_CONN_ID
-from common.sql import PostgresHook
+from common.sql import PostgresHook, _single_value
from database.batched_update import constants
logger = logging.getLogger(__name__)
-def _single_value(cursor):
- try:
- row = cursor.fetchone()
- return row[0]
- except Exception as e:
- raise ValueError("Unable to extract expected row data from cursor") from e
-
-
@task.branch
def resume_update(
resume_update: bool,
@@ -104,6 +96,9 @@ def update_batches(
task: AbstractOperator = None,
**kwargs,
):
+ if total_row_count == 0:
+ return 0
+
# Progress is tracked in an Airflow variable. When the task run starts, we resume
# from the start point set by this variable (defaulted to 0). This prevents the
# task from starting over at the beginning on retries.
diff --git a/catalog/dags/database/recreate_popularity_calculation_dag_factory.py b/catalog/dags/database/recreate_popularity_calculation_dag_factory.py
index 2770fab50..7381b1d28 100644
--- a/catalog/dags/database/recreate_popularity_calculation_dag_factory.py
+++ b/catalog/dags/database/recreate_popularity_calculation_dag_factory.py
@@ -89,20 +89,6 @@ def create_recreate_popularity_calculation_dag(data_refresh: DataRefresh):
),
)
- create_constants_view = PythonOperator(
- task_id="create_popularity_constants_view",
- python_callable=sql.create_media_popularity_constants_view,
- op_kwargs={
- "postgres_conn_id": POSTGRES_CONN_ID,
- "media_type": media_type,
- },
- execution_timeout=data_refresh.create_pop_constants_view_timeout,
- doc=(
- "Create the materialized view with popularity constants for each "
- "provider, using the percentile function."
- ),
- )
-
create_popularity_function = PythonOperator(
task_id="create_standardized_popularity_function",
python_callable=sql.create_standardized_media_popularity_function,
@@ -135,7 +121,6 @@ def create_recreate_popularity_calculation_dag(data_refresh: DataRefresh):
[drop_relations, drop_functions]
>> create_metrics_table
>> [update_metrics_table, create_percentile_function]
- >> create_constants_view
>> create_popularity_function
>> create_matview
)
diff --git a/catalog/dags/popularity/refresh_popularity_metrics_task_factory.py b/catalog/dags/popularity/refresh_popularity_metrics_task_factory.py
index f4e4e2170..428e23f74 100644
--- a/catalog/dags/popularity/refresh_popularity_metrics_task_factory.py
+++ b/catalog/dags/popularity/refresh_popularity_metrics_task_factory.py
@@ -19,8 +19,8 @@ from data_refresh.data_refresh_types import DataRefresh
GROUP_ID = "refresh_popularity_metrics_and_constants"
-UPDATE_MEDIA_POPULARITY_METRICS_TASK_ID = "update_media_popularity_metrics_table"
-UPDATE_MEDIA_POPULARITY_CONSTANTS_TASK_ID = "update_media_popularity_constants_view"
+UPDATE_MEDIA_POPULARITY_METRICS_TASK_ID = "update_media_popularity_metrics"
+UPDATE_MEDIA_POPULARITY_CONSTANTS_TASK_ID = "update_media_popularity_constants"
def create_refresh_popularity_metrics_task_group(
@@ -42,18 +42,17 @@ def create_refresh_popularity_metrics_task_group(
execution_timeout = refresh_config.refresh_metrics_timeout
with TaskGroup(group_id=GROUP_ID) as refresh_all_popularity_data:
- update_metrics = PythonOperator(
+ update_metrics = sql.update_media_popularity_metrics.override(
task_id=UPDATE_MEDIA_POPULARITY_METRICS_TASK_ID,
- python_callable=sql.update_media_popularity_metrics,
- op_kwargs={
- "postgres_conn_id": POSTGRES_CONN_ID,
- "media_type": media_type,
- },
execution_timeout=execution_timeout,
- doc=(
- "Updates the popularity metrics table, adding any new "
- "popularity metrics and updating the configured percentile."
- ),
+ )(
+ postgres_conn_id=POSTGRES_CONN_ID,
+ media_type=media_type,
+ )
+ update_metrics.doc = (
+ "Updates the metrics and target percentiles. If a popularity"
+ " metric is configured for a new provider, this step will add it"
+ " to the metrics table."
)
update_metrics_status = PythonOperator(
@@ -63,22 +62,33 @@ def create_refresh_popularity_metrics_task_group(
"media_type": media_type,
"dag_id": refresh_config.dag_id,
"message": "Popularity metrics update complete | "
- "_Next: popularity constants view update_",
+ "_Next: popularity constants update_",
},
)
- update_constants = PythonOperator(
- task_id=UPDATE_MEDIA_POPULARITY_CONSTANTS_TASK_ID,
- python_callable=sql.update_media_popularity_constants,
- op_kwargs={
- "postgres_conn_id": POSTGRES_CONN_ID,
- "media_type": media_type,
- },
- execution_timeout=execution_timeout,
- doc=(
- "Updates the popularity constants view. This completely "
- "recalculates the popularity constants for each provider."
- ),
+ update_constants = (
+ sql.update_percentile_and_constants_for_provider.override(
+ group_id=UPDATE_MEDIA_POPULARITY_CONSTANTS_TASK_ID,
+ )
+ .partial(
+ postgres_conn_id=POSTGRES_CONN_ID,
+ media_type=media_type,
+ execution_timeout=execution_timeout,
+ )
+ .expand(
+ provider=[
+ provider
+ for provider in sql.POPULARITY_METRICS_BY_MEDIA_TYPE[
+ media_type
+ ].keys()
+ ]
+ )
+ )
+ update_constants.doc = (
+ "Recalculate the percentile values and popularity constants"
+ " for each provider, and update them in the metrics table. The"
+ " popularity constants will be used to calculate standardized"
+ " popularity scores."
)
update_constants_status = PythonOperator(
@@ -87,12 +97,12 @@ def create_refresh_popularity_metrics_task_group(
op_kwargs={
"media_type": media_type,
"dag_id": refresh_config.dag_id,
- "message": "Popularity constants view update complete | "
+ "message": "Popularity constants update complete | "
"_Next: refresh matview_",
},
)
- update_metrics >> [update_constants, update_metrics_status]
+ update_metrics >> [update_metrics_status, update_constants]
update_constants >> update_constants_status
return refresh_all_popularity_data
diff --git a/catalog/tests/dags/common/loader/test_sql.py b/catalog/tests/dags/common/loader/test_sql.py
index 628f9d3a1..4569c77e4 100644
--- a/catalog/tests/dags/common/loader/test_sql.py
+++ b/catalog/tests/dags/common/loader/test_sql.py
@@ -37,11 +37,9 @@ def table_info(
return TableInfo(
image=image_table,
image_view=f"image_view_{identifier}",
- constants=f"image_popularity_constants_{identifier}",
metrics=f"image_popularity_metrics_{identifier}",
standardized_popularity=f"standardized_popularity_{identifier}",
popularity_percentile=f"popularity_percentile_{identifier}",
- pop_constants_idx=f"test_popularity_constants_{identifier}_idx",
image_view_idx=f"test_view_id_{identifier}_idx",
provider_fid_idx=f"test_view_provider_fid_{identifier}_idx",
)
@@ -84,7 +82,6 @@ def postgres_with_load_and_image_table(
DROP TABLE IF EXISTS {load_table} CASCADE;
DROP TABLE IF EXISTS {image_table} CASCADE;
DROP INDEX IF EXISTS {image_table}_provider_fid_idx;
- DROP MATERIALIZED VIEW IF EXISTS {table_info.constants} CASCADE;
DROP TABLE IF EXISTS {table_info.metrics} CASCADE;
DROP FUNCTION IF EXISTS {table_info.standardized_popularity} CASCADE;
DROP FUNCTION IF EXISTS {table_info.popularity_percentile} CASCADE;
diff --git a/catalog/tests/dags/common/popularity/test_sql.py b/catalog/tests/dags/common/popularity/test_sql.py
index d54f72a71..12b9285e3 100644
--- a/catalog/tests/dags/common/popularity/test_sql.py
+++ b/catalog/tests/dags/common/popularity/test_sql.py
@@ -21,11 +21,9 @@ POSTGRES_TEST_URI = os.getenv("AIRFLOW_CONN_POSTGRES_OPENLEDGER_TESTING")
class TableInfo(NamedTuple):
image: str
image_view: str
- constants: str
metrics: str
standardized_popularity: str
popularity_percentile: str
- pop_constants_idx: str
image_view_idx: str
provider_fid_idx: str
@@ -38,11 +36,9 @@ def table_info(
return TableInfo(
image=image_table,
image_view=f"image_view_{identifier}",
- constants=f"image_popularity_constants_{identifier}",
metrics=f"image_popularity_metrics_{identifier}",
standardized_popularity=f"standardized_popularity_{identifier}",
popularity_percentile=f"popularity_percentile_{identifier}",
- pop_constants_idx=f"test_popularity_constants_{identifier}_idx",
image_view_idx=f"test_view_id_{identifier}_idx",
provider_fid_idx=f"test_view_provider_fid_{identifier}_idx",
)
@@ -56,7 +52,6 @@ def postgres_with_image_table(table_info):
drop_test_relations_query = f"""
DROP MATERIALIZED VIEW IF EXISTS {table_info.image_view} CASCADE;
- DROP MATERIALIZED VIEW IF EXISTS {table_info.constants} CASCADE;
DROP TABLE IF EXISTS {table_info.metrics} CASCADE;
DROP TABLE IF EXISTS {table_info.image} CASCADE;
DROP FUNCTION IF EXISTS {table_info.standardized_popularity} CASCADE;
@@ -89,17 +84,37 @@ USING btree (provider, md5(foreign_identifier));
def _set_up_popularity_metrics(metrics_dict, table_info, mock_pg_hook_task):
conn_id = POSTGRES_CONN_ID
+ # Create metrics table
sql.create_media_popularity_metrics(
postgres_conn_id=conn_id,
popularity_metrics_table=table_info.metrics,
)
- sql.update_media_popularity_metrics(
+ # Insert values from metrics_dict into metrics table
+ sql.update_media_popularity_metrics.function(
postgres_conn_id=conn_id,
popularity_metrics=metrics_dict,
popularity_metrics_table=table_info.metrics,
task=mock_pg_hook_task,
)
+ # For each provider in metrics_dict, calculate the percentile and then
+ # update the percentile and popularity constant
+ for provider in metrics_dict.keys():
+ percentile_val = sql.calculate_media_popularity_percentile_value.function(
+ postgres_conn_id=conn_id,
+ provider=provider,
+ task=mock_pg_hook_task,
+ popularity_metrics_table=table_info.metrics,
+ popularity_percentile=table_info.popularity_percentile,
+ )
+ sql.update_percentile_and_constants_values_for_provider.function(
+ postgres_conn_id=conn_id,
+ provider=provider,
+ raw_percentile_value=percentile_val,
+ popularity_metrics_table=table_info.metrics,
+ popularity_metrics=metrics_dict,
+ )
+
def _set_up_popularity_percentile_function(table_info):
conn_id = POSTGRES_CONN_ID
@@ -117,18 +132,13 @@ def _set_up_popularity_constants(
table_info,
mock_pg_hook_task,
):
- conn_id = POSTGRES_CONN_ID
- _set_up_popularity_percentile_function(table_info)
- _set_up_popularity_metrics(metrics_dict, table_info, mock_pg_hook_task)
+ # Execute the data query first (typically, loads sample data into the media table)
pg.cursor.execute(data_query)
pg.connection.commit()
- sql.create_media_popularity_constants_view(
- conn_id,
- popularity_constants=table_info.constants,
- popularity_constants_idx=table_info.pop_constants_idx,
- popularity_metrics=table_info.metrics,
- popularity_percentile=table_info.popularity_percentile,
- )
+
+ # Then set up functions, metrics, and constants
+ _set_up_popularity_percentile_function(table_info)
+ _set_up_popularity_metrics(metrics_dict, table_info, mock_pg_hook_task)
def _set_up_std_popularity_func(
@@ -150,7 +160,7 @@ def _set_up_std_popularity_func(
conn_id,
mock_pg_hook_task,
function_name=table_info.standardized_popularity,
- popularity_constants=table_info.constants,
+ popularity_metrics=table_info.metrics,
)
@@ -270,7 +280,7 @@ def test_popularity_percentile_function_nones_when_missing_type(
assert actual_percentile_val is None
-def test_constants_view_adds_values_and_constants(
+def test_metrics_table_adds_values_and_constants(
postgres_with_image_table, table_info, mock_pg_hook_task
):
data_query = dedent(
@@ -315,18 +325,18 @@ def test_constants_view_adds_values_and_constants(
postgres_with_image_table, data_query, metrics, table_info, mock_pg_hook_task
)
- check_query = f"SELECT * FROM {table_info.constants};"
+ check_query = f"SELECT * FROM {table_info.metrics};"
postgres_with_image_table.cursor.execute(check_query)
expect_rows = [
- ("diff_provider", "comments", 0.8, 50.0, 50.0, 12.5),
- ("my_provider", "views", 0.5, 50.0, 50.0, 50.0),
+ ("diff_provider", "comments", 0.8, 50.0, 12.5),
+ ("my_provider", "views", 0.5, 50.0, 50.0),
]
sorted_rows = sorted(list(postgres_with_image_table.cursor), key=lambda x: x[0])
for expect_row, sorted_row in zip(expect_rows, sorted_rows):
assert expect_row == pytest.approx(sorted_row)
-def test_constants_view_handles_zeros_and_missing(
+def test_metrics_table_handles_zeros_and_missing_in_constants(
postgres_with_image_table, table_info, mock_pg_hook_task
):
data_query = dedent(
@@ -364,18 +374,20 @@ def test_constants_view_handles_zeros_and_missing(
"""
)
metrics = {
+ # Provider that has some records with popularity data
"my_provider": {"metric": "views", "percentile": 0.8},
+ # Provider that has a metric configured, but no records with data for that metric
"diff_provider": {"metric": "comments", "percentile": 0.8},
}
_set_up_popularity_constants(
postgres_with_image_table, data_query, metrics, table_info, mock_pg_hook_task
)
- check_query = f"SELECT * FROM {table_info.constants};"
+ check_query = f"SELECT * FROM {table_info.metrics};"
postgres_with_image_table.cursor.execute(check_query)
expect_rows = [
- ("diff_provider", "comments", 0.8, None, None, None),
- ("my_provider", "views", 0.8, 0.0, 1.0, 0.25),
+ ("diff_provider", "comments", 0.8, None, None),
+ ("my_provider", "views", 0.8, 1.0, 0.25),
]
sorted_rows = sorted(list(postgres_with_image_table.cursor), key=lambda x: x[0])
for expect_row, sorted_row in zip(expect_rows, sorted_rows):
@@ -417,7 +429,7 @@ def test_get_providers_with_popularity_data_for_media_type(
expected_providers = ["diff_provider", "my_provider"]
actual_providers = sql.get_providers_with_popularity_data_for_media_type(
- POSTGRES_CONN_ID, media_type="image", constants_view=table_info.constants
+ POSTGRES_CONN_ID, media_type="image", popularity_metrics=table_info.metrics
)
assert actual_providers == expected_providers
@@ -456,7 +468,7 @@ def test_standardized_popularity_function_calculates(
_set_up_std_popularity_func(
postgres_with_image_table, data_query, metrics, table_info, mock_pg_hook_task
)
- check_query = f"SELECT * FROM {table_info.constants};"
+ check_query = f"SELECT * FROM {table_info.metrics};"
postgres_with_image_table.cursor.execute(check_query)
print(list(postgres_with_image_table.cursor))
arg_list = [
diff --git a/docker/upstream_db/0004_openledger_image_view.sql b/docker/upstream_db/0004_openledger_image_view.sql
index 20dc28f49..efdf20607 100644
--- a/docker/upstream_db/0004_openledger_image_view.sql
+++ b/docker/upstream_db/0004_openledger_image_view.sql
@@ -1,7 +1,9 @@
CREATE TABLE public.image_popularity_metrics (
provider character varying(80) PRIMARY KEY,
metric character varying(80),
- percentile float
+ percentile float,
+ val float,
+ constant float
);
@@ -32,23 +34,10 @@ STABLE
RETURNS NULL ON NULL INPUT;
-CREATE MATERIALIZED VIEW public.image_popularity_constants AS
- WITH popularity_metric_values AS (
- SELECT
- *,
- image_popularity_percentile(provider, metric, percentile) AS val
- FROM image_popularity_metrics
- )
- SELECT *, ((1 - percentile) / percentile) * val AS constant
- FROM popularity_metric_values;
-
-CREATE UNIQUE INDEX ON image_popularity_constants (provider);
-
-
CREATE FUNCTION standardized_image_popularity(provider text, meta_data jsonb)
RETURNS FLOAT AS $$
SELECT ($2->>metric)::FLOAT / (($2->>metric)::FLOAT + constant)
- FROM image_popularity_constants WHERE provider=$1;
+ FROM image_popularity_metrics WHERE provider=$1;
$$
LANGUAGE SQL
STABLE
diff --git a/docker/upstream_db/0007_openledger_audio_view.sql b/docker/upstream_db/0007_openledger_audio_view.sql
index 573d91798..f73748e7f 100644
--- a/docker/upstream_db/0007_openledger_audio_view.sql
+++ b/docker/upstream_db/0007_openledger_audio_view.sql
@@ -1,7 +1,9 @@
CREATE TABLE public.audio_popularity_metrics (
provider character varying(80) PRIMARY KEY,
metric character varying(80),
- percentile float
+ percentile float,
+ val float,
+ constant float
);
@@ -26,23 +28,10 @@ STABLE
RETURNS NULL ON NULL INPUT;
-CREATE MATERIALIZED VIEW public.audio_popularity_constants AS
- WITH popularity_metric_values AS (
- SELECT
- *,
- audio_popularity_percentile(provider, metric, percentile) AS val
- FROM audio_popularity_metrics
- )
- SELECT *, ((1 - percentile) / percentile) * val AS constant
- FROM popularity_metric_values;
-
-CREATE UNIQUE INDEX ON audio_popularity_constants (provider);
-
-
CREATE FUNCTION standardized_audio_popularity(provider text, meta_data jsonb)
RETURNS FLOAT AS $$
SELECT ($2->>metric)::FLOAT / (($2->>metric)::FLOAT + constant)
- FROM audio_popularity_constants WHERE provider=$1;
+ FROM audio_popularity_metrics WHERE provider=$1;
$$
LANGUAGE SQL
STABLE