TheNeuralBit commented on a change in pull request #14398:
URL: https://github.com/apache/beam/pull/14398#discussion_r644335342
##########
File path: sdks/python/apache_beam/examples/dataframe/README.md
##########
@@ -143,3 +143,40 @@ Queens,81138
Staten Island,531
Unknown,28527
```
+
+## Flight Delay pipeline (added in 2.31.0)
+[`flight_delays.py`](./flight_delays.py) contains an implementation of
+a pipeline that processes the flight ontime data from
+`bigquery-samples.airline_ontime_data.flights`. It uses a conventional Beam
+pipeline to read from BigQuery, apply a 24-hour rolling window, and define a
+Beam schema for the data. Then it converts to DataFrames in order to perform
+a complex aggregation using `GroupBy.apply`, and write the result out with
+`to_csv`. Note that the DataFrame computation respects the 24-hour window
+applied above, and results are partitioned into separate files per day.
+
+### Running the pipeline
+To run the pipeline locally:
+
+```sh
+python -m apache_beam.examples.dataframe.flight_delays \
+ --start_date 2012-12-24 \
+ --end_date 2012-12-25 \
+ --output gs://<bucket>/<dir>/delays.csv \
+ --project <gcp-project> \
+ --temp_location gs://<bucket>/<dir>
+```
+
+Note a GCP `project` and `temp_location` are required for reading from
BigQuery.
+
+This will produce files like
+`gs://<bucket>/<dir>/delays.csv-2012-12-23T00:00:00-2012-12-24T00:00:00-XXXXX-of-YYYYY`
Review comment:
Whoops, just a typo. Fixed.
##########
File path: sdks/python/apache_beam/examples/dataframe/flight_delays.py
##########
@@ -0,0 +1,129 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+"""A word-counting workflow using dataframes."""
Review comment:
Done
##########
File path: sdks/python/apache_beam/examples/dataframe/flight_delays.py
##########
@@ -0,0 +1,129 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+"""A word-counting workflow using dataframes."""
+
+# pytype: skip-file
+
+from __future__ import absolute_import
+
+import argparse
+import logging
+
+import apache_beam as beam
+from apache_beam.dataframe.convert import to_dataframe
+from apache_beam.options.pipeline_options import PipelineOptions
+
+
+def get_delay_at_top_airports(aa):
Review comment:
Done
##########
File path: sdks/python/apache_beam/examples/dataframe/flight_delays.py
##########
@@ -0,0 +1,129 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+"""A word-counting workflow using dataframes."""
+
+# pytype: skip-file
+
+from __future__ import absolute_import
+
+import argparse
+import logging
+
+import apache_beam as beam
+from apache_beam.dataframe.convert import to_dataframe
+from apache_beam.options.pipeline_options import PipelineOptions
+
+
+def get_delay_at_top_airports(aa):
Review comment:
Done
##########
File path: sdks/python/apache_beam/examples/dataframe/flight_delays.py
##########
@@ -0,0 +1,129 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+"""A word-counting workflow using dataframes."""
+
+# pytype: skip-file
+
+from __future__ import absolute_import
+
+import argparse
+import logging
+
+import apache_beam as beam
+from apache_beam.dataframe.convert import to_dataframe
+from apache_beam.options.pipeline_options import PipelineOptions
+
+
+def get_delay_at_top_airports(aa):
+ arr = aa.rename(columns={'arrival_airport':
'airport'}).airport.value_counts()
+ dep = aa.rename(columns={
+ 'departure_airport': 'airport'
+ }).airport.value_counts()
+ total = arr + dep
+ # Note we keep all to include duplicates.
+ # This ensures the result is deterministic
+ top_airports = total.nlargest(10, keep='all')
+ return aa[aa['arrival_airport'].isin(top_airports.index.values)].mean()
+
+
+def input_date(date):
+ import datetime
+ parsed = datetime.datetime.strptime(date, '%Y-%m-%d')
+ if parsed > datetime.datetime(2012, 12, 31):
Review comment:
Good point, there is. Added another check for it.
##########
File path: sdks/python/apache_beam/examples/dataframe/flight_delays.py
##########
@@ -0,0 +1,129 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+"""A word-counting workflow using dataframes."""
+
+# pytype: skip-file
+
+from __future__ import absolute_import
+
+import argparse
+import logging
+
+import apache_beam as beam
+from apache_beam.dataframe.convert import to_dataframe
+from apache_beam.options.pipeline_options import PipelineOptions
+
+
+def get_delay_at_top_airports(aa):
+ arr = aa.rename(columns={'arrival_airport':
'airport'}).airport.value_counts()
+ dep = aa.rename(columns={
+ 'departure_airport': 'airport'
+ }).airport.value_counts()
+ total = arr + dep
+ # Note we keep all to include duplicates.
+ # This ensures the result is deterministic
+ top_airports = total.nlargest(10, keep='all')
+ return aa[aa['arrival_airport'].isin(top_airports.index.values)].mean()
+
+
+def input_date(date):
+ import datetime
+ parsed = datetime.datetime.strptime(date, '%Y-%m-%d')
+ if parsed > datetime.datetime(2012, 12, 31):
+ raise ValueError("There's no data after 2012-12-31")
+ return date
+
+
+def run_flight_delay_pipeline(
+ pipeline, start_date=None, end_date=None, output=None):
+ query = f"""
+ SELECT
+ date,
+ airline,
+ departure_airport,
+ arrival_airport,
+ departure_delay,
+ arrival_delay
+ FROM `bigquery-samples.airline_ontime_data.flights`
+ WHERE date >= '{start_date}' AND date <= '{end_date}'
+ """
+
+ # Import this here to avoid pickling the main session.
+ import time
+ import datetime
+ from apache_beam import window
+
+ def to_unixtime(s):
+ return time.mktime(datetime.datetime.strptime(s, "%Y-%m-%d").timetuple())
+
+ # The pipeline will be run on exiting the with block.
+ with pipeline as p:
+ tbl = (
+ p
+ | 'read table' >> beam.io.ReadFromBigQuery(
+ query=query, use_standard_sql=True)
+ | 'assign ts' >>
Review comment:
Done
##########
File path: sdks/python/apache_beam/examples/dataframe/flight_delays.py
##########
@@ -0,0 +1,129 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+"""A word-counting workflow using dataframes."""
+
+# pytype: skip-file
+
+from __future__ import absolute_import
+
+import argparse
+import logging
+
+import apache_beam as beam
+from apache_beam.dataframe.convert import to_dataframe
+from apache_beam.options.pipeline_options import PipelineOptions
+
+
+def get_delay_at_top_airports(aa):
+ arr = aa.rename(columns={'arrival_airport':
'airport'}).airport.value_counts()
+ dep = aa.rename(columns={
+ 'departure_airport': 'airport'
+ }).airport.value_counts()
+ total = arr + dep
+ # Note we keep all to include duplicates.
+ # This ensures the result is deterministic
+ top_airports = total.nlargest(10, keep='all')
+ return aa[aa['arrival_airport'].isin(top_airports.index.values)].mean()
+
+
+def input_date(date):
+ import datetime
+ parsed = datetime.datetime.strptime(date, '%Y-%m-%d')
+ if parsed > datetime.datetime(2012, 12, 31):
+ raise ValueError("There's no data after 2012-12-31")
+ return date
+
+
+def run_flight_delay_pipeline(
+ pipeline, start_date=None, end_date=None, output=None):
+ query = f"""
+ SELECT
+ date,
+ airline,
+ departure_airport,
+ arrival_airport,
+ departure_delay,
+ arrival_delay
+ FROM `bigquery-samples.airline_ontime_data.flights`
+ WHERE date >= '{start_date}' AND date <= '{end_date}'
+ """
+
+ # Import this here to avoid pickling the main session.
+ import time
+ import datetime
+ from apache_beam import window
+
+ def to_unixtime(s):
+ return time.mktime(datetime.datetime.strptime(s, "%Y-%m-%d").timetuple())
+
+ # The pipeline will be run on exiting the with block.
+ with pipeline as p:
+ tbl = (
+ p
+ | 'read table' >> beam.io.ReadFromBigQuery(
+ query=query, use_standard_sql=True)
+ | 'assign ts' >>
+ beam.Map(lambda x: window.TimestampedValue(x, to_unixtime(x['date'])))
+ | 'set schema' >> beam.Select(
+ date=lambda x: str(x['date']),
Review comment:
The casts make sure we get type information for the schema. Added a
comment about that.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
[email protected]