sshiv012 commented on code in PR #8773: URL: https://github.com/apache/texera/pull/8773#discussion_r4625132966
########## docs/tutorials/guide-to-use-python-udf/index.md: ########## @@ -0,0 +1,212 @@ +<!-- + ~ 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. +--> + +--- +title: "Guide to Use a Python UDF" +weight: 30 +--- + +A **Python UDF** (user-defined function) is an operator that runs a small piece of Python code you write. Use it when no built-in operator does what you need. + +You don't need to be a programmer. Copy the example below and change one line at a time. + +## Which Python operator should I use? + +| You want to… | Use | +|---|---| +| Add or change a column with a one-line formula, e.g. `tuple_["Units Sold"] * 2` | **Python Lambda Function** (no class to write) | +| Turn a whole table into one summary row, e.g. `table["Units Sold"].mean()` | **Python Table Reducer** (no class to write) | +| Anything else with one or more inputs | **Python UDF** | +| Apply a model (input 0) to data rows (input 1) | **2-in Python UDF** | +| Create data from nothing (no input) | **1-out Python UDF** | + +## Your first UDF in 4 steps + +This example adds a `Revenue` column (units × price) to the sales data from [the dataset tutorial](../create-dataset-upload-data/). + +**1. Add the operator.** Drag **Python UDF** (under *User-defined Functions → Python*) onto the canvas and connect your data to it. + +**2. Write the code.** Click **Edit code content**. The editor opens with a template. Its classes are commented out (their lines start with `#`), so running it unchanged fails. Uncomment one class, or replace everything with: + +```python +from pytexera import * + + +class ProcessTupleOperator(UDFOperatorV2): + + @overrides + def process_tuple(self, tuple_: Tuple, port: int) -> Iterator[Optional[TupleLike]]: + tuple_["Revenue"] = tuple_["Units Sold"] * tuple_["Unit Price"] + yield tuple_ +``` + + + +**3. Declare the new column.** In the property panel, under **Extra output column(s)**, click **+** and add `Revenue` with type `double`. Leave **Retain input columns** checked to keep the original columns. + +<img src="udf-output-columns.png" alt="Retain input columns and one extra output column named Revenue" width="260"> + +**4. Run.** Click the eye icon on the UDF, then **Run**. Click the UDF, then the **Result** tab in the result panel. + +## The 5 rules + +Almost every UDF problem comes from breaking one of these. + +| # | Rule | If you break it | +|---|---|---| +| 1 | `from pytexera import *` is at the top (the template already has it) | `name 'UDFOperatorV2' is not defined` | +| 2 | Exactly **one** class. Delete or comment out the others. | `There should be one and only one Operator defined` | +| 3 | The method name must match the class you inherit from (table below) | `... does not implement process_tuple` or `... No super class method found` | +| 4 | Send results with `yield`, never `return` a value | ``process_tuple must `yield` results, not `return` them`` | +| 5 | The columns you yield must match the output columns (step 3) | `expected but missing` or `unexpected field` | + +## How your code receives data + +Pick one row of this table. The class name in brackets and the method name must go together. + +| Class `(…)` | Method you write | You receive | Good for | +|---|---|---|---| +| `UDFOperatorV2` | `process_tuple(self, tuple_, port)` | one row at a time (use it like a dict: `tuple_["col"]`) | per-row formulas, filtering | +| `UDFBatchOperator` | `process_batch(self, batch, port)` | `BATCH_SIZE` rows at a time, as a pandas DataFrame | calling an API in chunks | +| `UDFTableOperator` | `process_table(self, table, port)` | **all** rows of one input, as a pandas DataFrame | sorting, statistics, ML training | +| `UDFSourceOperator` (1-out UDF only) | `produce(self)` | nothing; you create the data | generating or downloading data | + +What you can `yield`: + +- **A row**: a `Tuple` or a `dict`, e.g. `yield {"name": "a", "value": 1}`. +- **A table**: a pandas `DataFrame` or `Table`. Yield the DataFrame itself, not a dict that contains DataFrames. +- **`None`**: produce nothing for this input. + +To drop a row, just don't `yield` it. To output several rows, `yield` several times. + +## One-time setup (loading a model, opening a file) + +Put setup code in `open()`, which runs once before any data arrives: Review Comment: Will add both next to open(). I noted that on_finish is for UDFOperatorV2 and UDFBatchOperator, since table and source operators already use it themselves. -- 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. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
