Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

gcp.py 4.4 KB

You have to be logged in to leave a comment. Sign In
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
  1. import datetime
  2. import logging
  3. import os
  4. import tempfile
  5. from os import path
  6. import pandas as pd
  7. from airflow.models import DAG
  8. from airflow.operators.python import PythonOperator
  9. from airflow.providers.google.cloud.hooks.gcs import GCSHook
  10. from airflow.providers.google.cloud.operators.bigquery import (
  11. BigQueryExecuteQueryOperator,
  12. BigQueryDeleteTableOperator,
  13. )
  14. from airflow.providers.google.cloud.transfers.bigquery_to_gcs import (
  15. BigQueryToGCSOperator,
  16. )
  17. from airflow.providers.google.cloud.transfers.gcs_to_bigquery import (
  18. GCSToBigQueryOperator,
  19. )
  20. from custom.hooks import MovielensHook
  21. dag = DAG(
  22. "gcp_movie_ranking",
  23. start_date=datetime.datetime(year=2019, month=1, day=1),
  24. end_date=datetime.datetime(year=2019, month=3, day=1),
  25. schedule_interval="@monthly",
  26. default_args={"depends_on_past": True},
  27. )
  28. def _fetch_ratings(api_conn_id, gcp_conn_id, gcs_bucket, **context):
  29. year = context["execution_date"].year
  30. month = context["execution_date"].month
  31. # Fetch ratings from our API.
  32. logging.info(f"Fetching ratings for {year}/{month:02d}")
  33. api_hook = MovielensHook(conn_id=api_conn_id)
  34. ratings = pd.DataFrame.from_records(
  35. api_hook.get_ratings_for_month(year=year, month=month),
  36. columns=["userId", "movieId", "rating", "timestamp"],
  37. )
  38. logging.info(f"Fetched {ratings.shape[0]} rows")
  39. # Write ratings to temp file.
  40. with tempfile.TemporaryDirectory() as tmp_dir:
  41. tmp_path = path.join(tmp_dir, "ratings.csv")
  42. ratings.to_csv(tmp_path, index=False)
  43. # Upload file to GCS.
  44. logging.info(f"Writing results to ratings/{year}/{month:02d}.csv")
  45. gcs_hook = GCSHook(gcp_conn_id)
  46. gcs_hook.upload(
  47. bucket_name=gcs_bucket,
  48. object_name=f"ratings/{year}/{month:02d}.csv",
  49. filename=tmp_path,
  50. )
  51. fetch_ratings = PythonOperator(
  52. task_id="fetch_ratings",
  53. python_callable=_fetch_ratings,
  54. op_kwargs={
  55. "api_conn_id": "movielens",
  56. "gcp_conn_id": "gcp",
  57. "gcs_bucket": os.environ["RATINGS_BUCKET"],
  58. },
  59. dag=dag,
  60. )
  61. import_in_bigquery = GCSToBigQueryOperator(
  62. task_id="import_in_bigquery",
  63. bucket=os.environ["RATINGS_BUCKET"],
  64. source_objects=[
  65. "ratings/{{ execution_date.year }}/{{ execution_date.strftime('%m') }}.csv"
  66. ],
  67. source_format="CSV",
  68. create_disposition="CREATE_IF_NEEDED",
  69. write_disposition="WRITE_TRUNCATE",
  70. bigquery_conn_id="gcp",
  71. skip_leading_rows=1,
  72. schema_fields=[
  73. {"name": "userId", "type": "INTEGER"},
  74. {"name": "movieId", "type": "INTEGER"},
  75. {"name": "rating", "type": "FLOAT"},
  76. {"name": "timestamp", "type": "TIMESTAMP"},
  77. ],
  78. destination_project_dataset_table=(
  79. os.environ["GCP_PROJECT"]
  80. + ":"
  81. + os.environ["BIGQUERY_DATASET"]
  82. + "."
  83. + "ratings${{ ds_nodash }}"
  84. ),
  85. dag=dag,
  86. )
  87. query_top_ratings = BigQueryExecuteQueryOperator(
  88. task_id="query_top_ratings",
  89. destination_dataset_table=(
  90. os.environ["GCP_PROJECT"]
  91. + ":"
  92. + os.environ["BIGQUERY_DATASET"]
  93. + "."
  94. + "rating_results_{{ ds_nodash }}"
  95. ),
  96. sql=(
  97. "SELECT movieid, AVG(rating) as avg_rating, COUNT(*) as num_ratings "
  98. "FROM " + os.environ["BIGQUERY_DATASET"] + ".ratings "
  99. "WHERE DATE(timestamp) <= DATE({{ ds }}) "
  100. "GROUP BY movieid "
  101. "ORDER BY avg_rating DESC"
  102. ),
  103. write_disposition="WRITE_TRUNCATE",
  104. create_disposition="CREATE_IF_NEEDED",
  105. bigquery_conn_id="gcp",
  106. dag=dag,
  107. )
  108. extract_top_ratings = BigQueryToGCSOperator(
  109. task_id="extract_top_ratings",
  110. source_project_dataset_table=(
  111. os.environ["GCP_PROJECT"]
  112. + ":"
  113. + os.environ["BIGQUERY_DATASET"]
  114. + "."
  115. + "rating_results_{{ ds_nodash }}"
  116. ),
  117. destination_cloud_storage_uris=[
  118. "gs://" + os.environ["RESULT_BUCKET"] + "/{{ ds_nodash }}.csv"
  119. ],
  120. export_format="CSV",
  121. bigquery_conn_id="gcp",
  122. dag=dag,
  123. )
  124. delete_result_table = BigQueryDeleteTableOperator(
  125. task_id="delete_result_table",
  126. deletion_dataset_table=(
  127. os.environ["GCP_PROJECT"]
  128. + ":"
  129. + os.environ["BIGQUERY_DATASET"]
  130. + "."
  131. + "rating_results_{{ ds_nodash }}"
  132. ),
  133. bigquery_conn_id="gcp",
  134. dag=dag,
  135. )
  136. fetch_ratings >> import_in_bigquery >> query_top_ratings >> extract_top_ratings >> delete_result_table
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...