concept rating in category apache airflow

appears as: ratings, ratings, rating
Data Pipelines with Apache Airflow

This is an excerpt from Manning's book Data Pipelines with Apache Airflow.

Before building any custom components, let’s first try solving our problem using the (by now familiar) PythonOperator. In this case, we’re interested in building a recommender system which will recommend which new movie(s) to watch depending on our view history. However, as an initial pilot project we decide to focus on simply getting in our data, which concerns past ratings of users for a given set of movies, and recommending the movies which seem to be most popular overall based on their ratings.

Now we have our _get_ratings function, we can call this function using the PythonOperator to fetch ratings for each schedule interval. Once we have the ratings, we can dump the results into a JSON output file, partitioned by date so that we can easily re-run fetches if needed.

We can implement this functionality by writing a small wrapper function that takes care of supplying the start/end dates and writing the ratings to an output function:

Listing 7.12
def _fetch_ratings(templates_dict, batch_size=1000, **_):
   logger = logging.getLogger(__name__) #A
 
   start_date = templates_dict["start_date"] #B
   end_date = templates_dict["end_date"]
   output_path = templates_dict["output_path"]
 
   logger.info(f"Fetching ratings for {start_date} to {end_date}")
   ratings = list( #C
       _get_ratings(
           start_date=start_date,
           end_date=end_date,
           batch_size=batch_size,
       )
   )
   logger.info(f"Fetched {len(ratings)} ratings")
 
   logger.info(f"Writing ratings to {output_path}")
 
   # Make sure the output directory exists.
   output_dir = os.path.dirname(output_path) #D
   os.makedirs(output_dir, exist_ok=True)
 
   with open(output_path, "w") as file_: #E
       json.dump(ratings, fp=file_)
 
fetch_ratings = PythonOperator( #F
   task_id="fetch_ratings",
   python_callable=_fetch_ratings,
   templates_dict={
       "start_date": "{{ds}}",
       "end_date": "{{next_ds}}",
       "output_path": "/data/python_operator/ratings/{{ds}}.json",
   },
   provide_context=True,
)
 
Figure 13.43 Overview of our initial GCP movie ranking DAG, containing steps to download ratings from the ratings API and upload them into Google Cloud Storage.