Openverse is a search engine for openly-licensed media. This monorepo includes all application code.
Get change in record counts during data refresh from Elasticsearch (#4067)
mjtungb3520a705ef2
diff --git a/catalog/dags/common/elasticsearch.py b/catalog/dags/common/elasticsearch.pyindex 16ef8332d..048133594 100644--- a/catalog/dags/common/elasticsearch.py+++ b/catalog/dags/common/elasticsearch.py@@ -78,6 +78,33 @@ def remove_excluded_index_settings(index_config):return index_config+@task+def get_record_count_group_by_sources(es_host: str, index: str):+ """+ Return a dict where the keys are the sources, and the values are the counts.+ Calls Elasticsearch to run an aggs query to do a count grouped by the field "source", and parses the result into a dict.+ """+ body = {"aggs": {"unique_sources": {"terms": {"field": "source"}}}}++ # Unfornately the ElasticsearchPythonHook's search function doesn't work with aggs, because it returns the "hits" key only+ # See source code at https://airflow.apache.org/docs/apache-airflow-providers-elasticsearch/stable/_modules/airflow/providers/elasticsearch/hooks/elasticsearch.html#ElasticsearchPythonHook+ # Therefore using get_conn to call the search from the ES client+ es_client = ElasticsearchPythonHook(hosts=[es_host]).get_conn+ try:+ es_result = es_client.search(body=body, index=index)+ except NotFoundError as err:+ logger.warning(f"Elasticsearch index: {index} does not exist. Error msg: {err}")+ return {}++ # es_buckets object looks like: [{'key': 'flickr', 'doc_count': 2500}, {'key': 'stocksnap', 'doc_count': 2500}]+ es_buckets = es_result["aggregations"]["unique_sources"]["buckets"]+ result = {+ source_count["key"]: source_count["doc_count"] for source_count in es_buckets+ }++ return result++@taskdef create_index(index_config, es_host: str):es_conn = ElasticsearchPythonHook(hosts=[es_host]).get_conndiff --git a/catalog/dags/data_refresh/dag_factory.py b/catalog/dags/data_refresh/dag_factory.pyindex c9d702637..839aa3e54 100644--- a/catalog/dags/data_refresh/dag_factory.py+++ b/catalog/dags/data_refresh/dag_factory.py@@ -28,14 +28,14 @@ from collections.abc import Sequencefrom airflow import DAGfrom airflow.operators.python import PythonOperator+from airflow.utils.trigger_rule import TriggerRule+from common import elasticsearch as esfrom common.constants import (DAG_DEFAULT_ARGS,- OPENLEDGER_API_CONN_ID,- XCOM_PULL_TEMPLATE,+ PRODUCTION,)from common.sensors.constants import PRODUCTION_ES_CONCURRENCY_TAG-from common.sql import PGExecuteQueryOperator, single_valuefrom data_refresh.data_refresh_task_factory import create_data_refresh_task_groupfrom data_refresh.data_refresh_types import DATA_REFRESH_CONFIGS, DataRefreshfrom data_refresh.reporting import report_record_difference@@ -75,27 +75,14 @@ def create_data_refresh_dag(data_refresh: DataRefresh, external_dag_ids: Sequenc)with dag:- # Count estimate SQL for determining the number of rows in the API table. While- # this query is not exact, it is close to accurate since the API media table- # does not receive many (if any) updates/insertions/deletions once the data- # refresh is complete. In testing this was shown to be accurate and fast- # (~0.000002% off and 1/14000th of the execution time). However, the reality is- # that this count is *not* exact, so we show it as an estimate in reports.- count_sql = f"""- SELECT c.reltuples::bigint AS estimate- FROM pg_class c- JOIN pg_namespace n ON n.oid = c.relnamespace- WHERE c.relname = '{data_refresh.media_type}'- AND n.nspname = 'public';- """+ es_host = es.get_es_host(environment=PRODUCTION)# Get the current number of records in the target API table- before_record_count = PGExecuteQueryOperator(- task_id="get_before_record_count",- conn_id=OPENLEDGER_API_CONN_ID,- sql=count_sql,- handler=single_value,- return_last=True,+ before_record_count = es.get_record_count_group_by_sources.override(+ task_id="get_before_record_count"+ )(+ es_host=es_host,+ index=data_refresh.media_type,)# Trigger the data refresh on the remote ingestion server, and wait@@ -105,12 +92,11 @@ def create_data_refresh_dag(data_refresh: DataRefresh, external_dag_ids: Sequenc)# Get the final number of records in the API table after the refresh- after_record_count = PGExecuteQueryOperator(- task_id="get_after_record_count",- conn_id=OPENLEDGER_API_CONN_ID,- sql=count_sql,- handler=single_value,- return_last=True,+ after_record_count = es.get_record_count_group_by_sources.override(+ task_id="get_after_record_count", trigger_rule=TriggerRule.NONE_FAILED+ )(+ es_host=es_host,+ index=data_refresh.media_type,)# Report the count difference to Slack@@ -118,12 +104,8 @@ def create_data_refresh_dag(data_refresh: DataRefresh, external_dag_ids: Sequenctask_id="report_record_counts",python_callable=report_record_difference,op_kwargs={- "before": XCOM_PULL_TEMPLATE.format(- before_record_count.task_id, "return_value"- ),- "after": XCOM_PULL_TEMPLATE.format(- after_record_count.task_id, "return_value"- ),+ "before": before_record_count,+ "after": after_record_count,"media_type": data_refresh.media_type,"dag_id": data_refresh.dag_id,},diff --git a/catalog/dags/data_refresh/reporting.py b/catalog/dags/data_refresh/reporting.pyindex 967ef32fa..786237b0d 100644--- a/catalog/dags/data_refresh/reporting.py+++ b/catalog/dags/data_refresh/reporting.py@@ -17,21 +17,31 @@ def report_status(media_type: str, message: str, dag_id: str):return message-def report_record_difference(before: str, after: str, media_type: str, dag_id: str):- before = int(before)- after = int(after)- count_diff = after - before- percent_diff = (count_diff / before) * 100- # Note for formatting:- # '+' - number will always have a sign in front of it- # ',' - number is comma separated- # '.' - number is a float+def report_record_difference(before: dict, after: dict, media_type: str, dag_id: str):+ all_keys = before.keys() | after.keys()+ total_before = sum(before.values())+ total_after = sum(after.values())+ count_diff = total_after - total_before+ if total_before > 0:+ percent_diff = (count_diff / total_before) * 100+ else:+ percent_diff = float("inf")+ breakdown_diff = {k: after.get(k, 0) - before.get(k, 0) for k in all_keys}+ if breakdown_diff:+ breakdown_message = "\n".join(+ f"`{k}`:{v:+,}" for k, v in breakdown_diff.items()+ )+ else:+ breakdown_message = "Both indices missing? No breakdown to show"+message = f"""Data refresh for {media_type} complete! :tada:-_Note: All values are row estimates and are not (but nearly) exact_-*Record count difference for `{media_type}`*: {before:,} → {after:,}+_Note: All values are retrieved from elasticsearch_+*Record count difference for `{media_type}`*: {total_before:,} → {total_after:,}*Change*: {count_diff:+,} ({percent_diff:+}% Δ)+*Breakdown of changes*:"""+ message += breakdown_messageslack.send_message(text=message, dag_id=dag_id, username="Data refresh record difference")diff --git a/catalog/tests/dags/data_refresh/test_reporting.py b/catalog/tests/dags/data_refresh/test_reporting.pyindex 1aaf2df1c..d37415a14 100644--- a/catalog/tests/dags/data_refresh/test_reporting.py+++ b/catalog/tests/dags/data_refresh/test_reporting.py@@ -6,10 +6,37 @@ from data_refresh.reporting import report_record_difference, report_status@pytest.mark.parametrize("before, after, expected_in_message",[- ["1", "2", ["1 → 2", "+1 (+100.0%"]],- ["1", "3", ["1 → 3", "+2 (+200.0%"]],- ["4", "2", ["4 → 2", "-2 (-50.0%"]],- ["4000", "2000", ["4,000 → 2,000", "-2,000 (-50.0%"]],+ [+ {"src1": 1, "src2": 19},+ {"src1": 2, "src2": 38},+ ["20 → 40", "+20 (+100.0%", "`src1`:+1", "`src2`:+19"],+ ],+ [+ {"src1": 1, "src2": 19},+ {"src1": 3, "src2": 57, "src3": 20},+ ["20 → 80", "+60 (+300.0%", "`src1`:+2", "`src2`:+38", "`src3`:+20"],+ ],+ [+ {"src1": 4, "src2": 21},+ {"src1": 4},+ ["25 → 4", "-21 (-84.0%", "`src1`:+0", "`src2`:-21"],+ ],+ [+ {"src1": 4000, "src2": 20},+ {"src1": 2000, "src2": 10},+ ["4,020 → 2,010", "-2,010 (-50.0%", "`src1`:-2,000", "`src2`:-10"],+ ],+ [+ {},+ {"src1": 10, "src2": 10},+ ["0 → 20", "+20 (+inf%", "`src1`:+10", "`src2`:+10"],+ ],+ [+ {"src1": 10, "src2": 10},+ {},+ ["20 → 0", "-20 (-100.0%", "`src1`:-10", "`src2`:-10"],+ ],+ [{}, {}, ["Both indices missing? No breakdown to show"]],],)def test_record_reporting(before, after, expected_in_message):