Repository navigation
Conversation
Add a new code sample for a batch pipeline that reads CSV sales records from Cloud Storage with ReadFromText, totals sales per product with CombinePerKey, and writes the results back to Cloud Storage with WriteToText.
|
Here is the summary of changes. You are about to add 1 region tag.
This comment is generated by snippet-bot.
|
There was a problem hiding this comment.
Code Review
This pull request introduces a new Apache Beam pipeline snippet in Python (batch_process_storage.py) that reads CSV data from Google Cloud Storage, aggregates sales amounts by product, and writes the results back to GCS. The review feedback highlights a potential issue where parsing CSV lines using a simple split(',') without error handling could crash the pipeline on malformed rows. To make the pipeline more resilient, the reviewer suggests refactoring parse_record to yield parsed records safely within a try-except block, importing Iterable for typing, and updating the pipeline step to use beam.FlatMap instead of beam.Map.
|
|
||
| # [START dataflow_batch_process_storage] | ||
| import argparse | ||
| from typing import List, Optional, Tuple |
| def parse_record(line: str) -> Tuple[str, float]: | ||
| """Parses a CSV line into a (product, amount) tuple.""" | ||
| _, product, amount = line.split(",") | ||
| return product, float(amount) |
There was a problem hiding this comment.
Parsing CSV lines directly using split(',') without error handling can crash the entire pipeline if there are empty lines, headers, or malformed rows (e.g., raising ValueError during unpacking or float conversion).
Using a generator that yields results only on successful parsing, combined with beam.FlatMap, makes the pipeline resilient to malformed input.
| def parse_record(line: str) -> Tuple[str, float]: | |
| """Parses a CSV line into a (product, amount) tuple.""" | |
| _, product, amount = line.split(",") | |
| return product, float(amount) | |
| def parse_record(line: str) -> Iterable[Tuple[str, float]]: | |
| """Parses a CSV line into a (product, amount) tuple.""" | |
| try: | |
| parts = line.split(",") | |
| if len(parts) >= 3: | |
| yield parts[1], float(parts[2]) | |
| except ValueError: | |
| pass |
| pipeline | ||
| | "ReadFromGCS" | ||
| >> beam.io.ReadFromText(known_args.input, skip_header_lines=1) | ||
| | "Parse" >> beam.Map(parse_record) |
Add a new code sample for a batch pipeline that reads CSV sales records from Cloud Storage with ReadFromText, totals sales per product with CombinePerKey, and writes the results back to Cloud Storage with WriteToText.
Description
Fixes # http://b/589715201
Checklist
Testing
Compliance & Style
Post-Approval Actions