Creating Javascript User-defined Functions

With SQL Stream Builder, you can create user functions to write powerful functions in JavaScript that you can use to enhance the functionality of SQL.

User functions can be simple translation functions like Celsius to Fahrenheit, more complex business logic, or even looking up data from external sources. User functions are written in JavaScript. When you write them, you create a library of useful functions.
  1. Navigate to the Streaming SQL Console.
    1. Navigate to Management Console > Environments, and select the environment where you have created your cluster.
    2. Select the Streaming Analytics cluster from the list of Data Hub clusters.
    3. Select Streaming SQL Console from the list of services.
      The Streaming SQL Console opens in a new window.
  2. Open a project from the Projects page of Streaming SQL Console.
    1. Select an already existing project from the list by clicking the Open button or Switch button.
    2. Create a new project by clicking the New Project button.
    3. Import a project by clicking the Import button.
    You are redirected to the Explorer view of the project.
  3. Click next to Functions.
  4. Click New Function.
  5. Add a Name to the UDF.
    For example, name the UDF to HELLO_WORLD.
  6. Add a Description to the UDF.
  7. Select the Output and Input data type.
    For example, select STRING.
  8. Paste the JavaScript code to the editor.
    For example:
    // check to see if the card is VISA
    function HELLO_WORLD(card){
        var cardType = "Other";
        if (card.charAt(0) == 4){
          cardType = "Visa";
        }
        return cardType;
    }
    HELLO_WORLD($p0); // this line must exist
    
  9. Click Create.
  10. Once created, you can use a User Function in your SQL statement:
    For example:
    -- simple usage
    SELECT HELLO_WORLD(card) AS IS_VISA
    FROM ev_sample_fraud;
    
    -- in the predicate
    SELECT amount, card
    FROM ev_sample_fraud
    WHERE HELLO_WORLD(card) = "Visa";