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.
| 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 |
There was a problem hiding this comment.
Thanks, but I'm keeping parse_record as is on purpose. This is a docs snippet, so the goal is to show the core read → parse → aggregate → write pattern as clearly as possible.
-
The header row is already handled by
ReadFromText(..., skip_header_lines=1), and the sample assumes well-formed input. -
except ValueError: passwould silently drop bad rows and produce wrong totals with no signal. I'd rather not teach readers that pattern. In production you'd send bad records to a dead-letter output, which is beyond the scope of this snippet. -
len(parts) >= 3would also quietly accept rows with extra columns, which hides a different kind of bad data.
| pipeline | ||
| | "ReadFromGCS" | ||
| >> beam.io.ReadFromText(known_args.input, skip_header_lines=1) | ||
| | "Parse" >> beam.Map(parse_record) |
There was a problem hiding this comment.
Not adopting: FlatMap is only needed if parse_record becomes a generator, which I'm declining (see the thread on that function). Since parse_record returns exactly one (product, amount) tuple per line, beam.Map is the right transform.
|
hey @cbonnie, Thanks for this sample. I ran it unmodified on Dataflow (DataflowRunner, Beam 2.76.0, Python 3.14) against two CSV files in Cloud Storage. The job finished and the per-product totals matched values I computed separately. It also passes the repo's flake8 and black checks. Kokoro is not running at the moment, so ignore its failure statuses on this PR. Two requests before merging:
dataflow/snippets/tests/test_batch_process_storage.py
Describing the format in the --input help text or a docstring on run is enough, for example: "CSV files with a header row and three columns: order ID, product, amount." Parsing with the csv module would also make quoted fields work. I would not skip bad rows silently, as the automated review suggests: for a sales total, a failed job is better than a wrong number. Optional:
|
iennae
left a comment
There was a problem hiding this comment.
Please add a test and state the inputs required.
|
Hi @iennae, thank you for the review. Here's the PR for the test for this sample: #15024 Also updated this batch processing sample as you suggested. I chose to keep |
Add expected input in docstring. Parse rows with the `csv` module.
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.
Code sample will be used here: http://cl/1013782122
Description
Addresses # http://b/589715201
Checklist
Testing
Compliance & Style
Post-Approval Actions