Sunday, April 10, 2016

Ternary Operators in U-SQL

In C#, the ternary operator tests a condition. It compares two values. It produces a third value that depends on the result of the comparison. In U-SQL this can be achieved using the conditional operator as shown below and not using If statement as if is not supported by U-SQL. Applying this in our query sample
@searchlog = 
EXTRACT UserId          int, 
            Start           DateTime, 
            Region          string, 
            Query           string, 
            Duration        int, 
            Urls            string, 
            ClickedUrls     string
    FROM @"/Samples/Data/SearchLog.tsv"
    USING Extractors.Tsv();

@output = 
    SELECT 
        Region,  
         (Duration>300 ? "long" :"short") AS DwellType
    FROM @searchlog;

OUTPUT @output
    TO @"/Samples/Output/SearchLog_output.tsv"
    USING Outputters.Tsv();
Understand the importance of using Parentheses with the Conditional Operator Always enclose the conditional operator in parenthesis to C# Precedence rules. Fro example, the below statement without the parenthesis
c1 ? true : false AND c2 ? true : false
It will be evaluated as below without parenthesis, which we don’t want to happen
c1 ? true : (false AND c2 ? True : false)
To prevent this from happening just get into the habit of always using parenthesis around a conditional operator as shown below
(c1 ? True : false) AND (c2 ? True : false)