Adding Python user-defined functions

Write a Python user-defined function in the Streaming SQL Console, and call it in the SQL of your jobs or as a computed column in a table.

  • A bucket is bound to the default purpose of the Cloudera Streaming Analytics engine instance. Without it, the Functions node is not available.
  • Your function uses Python 3.11, which is the Python version of the engine instance.
  1. In the Streaming SQL Console, click Projects in the left navigation pane, and click the name of your project.
    The project opens, with the Explorer panel on the left. To open the Streaming SQL Console, see Accessing Cloudera SQL Stream Builder.
  2. In the Explorer, open the menu of Functions, and click New Function.
    The function editor opens with a sample function. The Language property is displayed as Python.
  3. In Name, enter a name for the function.
    The name is how you call the function in SQL. For example, enter ADD_FUNCTION.
  4. Optional: Optional: In Description, enter a description of the function.
  5. In the Function editor, enter the Python code.

    The following example adds two numbers:

    from pyflink.table.udf import udf
    from pyflink.table import DataTypes
    
    @udf(result_type=DataTypes.BIGINT())
    def udf_function(i, j):
        return i + j
  6. Click Create.
    The function is listed under Functions. To change it later, open it from the list, edit the code, and click Save.
  7. Use the function in the SQL of a job, or as a computed column when you create a table.
    -- as a SQL statement
    SELECT ADD_FUNCTION(myTable.n1, myTable.n2)
    FROM myTable;
    
    -- as a computed column
    CREATE TABLE myTable (
      `number_a` BIGINT,
      `number_b` BIGINT,
      `sum` AS ADD_FUNCTION(number_a, number_b)
    ) WITH (
      'connector' = 'kafka'
      -- more connector properties
    );

When a job that uses the function starts, Cloudera SQL Stream Builder (SSB) uploads the Python file to the bucket that is bound to the engine instance so that Flink can run it.

For more information about Python user-defined functions, see User-defined functions in the Apache Flink documentation.