Talend Open Studio Cookbook
上QQ阅读APP看书,第一时间看更新

Using intermediate variables in tMap

The tMap component is the most flexible and most used component in Talend, despite having the limitation on multiple lines for an expression. In the previous recipe, we saw how ternary expressions can be used to extend the capability of the tMap expressions. In this recipe, we will see that the tMap variables can also extend the capability of tMap.

Getting ready

Open the job jo_cook_ch04_0040_tMapVariables.

How to do it…

  1. In the Var section, click + to add a new variable, set the name to paymentTotal and Type to float, as shown in the following screenshot:
    How to do it…
  2. Insert the following code into the expression field:
    customer.payment1+customer.payment2+customer.payment3+customer.payment4+customer.payment5+customer.payment6
  3. Repeat step 1 for a variable named averageLastSixMonths with Type set to float, and a variable named averageAnnual also with Type set to float.
  4. Select paymentTotalRow by clicking the left mouse button.
  5. Drag the paymentTotalRow variable into the Expression column for the new variable averageLastSixMonths.
  6. Add /6 to the end of the expression to get:
    Var.paymentTotal / 6
  7. Drag the input column annualTotal into the Expression column for the variable averageAnnual and add /12 to the end of the expression.
  8. Add a final float variable called variance.
  9. Drag in the variable averageLastSixMonths add (minus) then drag in the variable averageAnnual.
  10. Highlight all the four columns using the Shift and right mouse click method and add them to the end of the output table.
  11. Your tMap should now look like the following screenshot:
    How to do it…
  12. Run the job to show the results.

How it works…

The variables are created in a structure called Var. New columns can be added to Var and can be assigned expressions just like output columns and also copied to output columns, just like input columns.

These variables can also be dragged and dropped in the same way that the input columns can, which means that the methods mentioned in the section tMap time savers can also be applied to the tMap variables

There's more…

As you can see, the tMap variables allow us to create new variables that enable us to build complex mappings using many variables, and then these variables can then be used in later variables, just like in normal Java coding.

As usual though, it is advisable to keep the number of new variables low in tMap to avoid maintenance headaches.

Tip

If you find that you are using many variables, and the code is becoming very complex then consider splitting tMap into multiple simpler tMaps or creating one or more code routines or using tJavaRow; with the advantage of using code routines or tJavaRow being that inline comments can be added to document the code, thus making it easier to debug and maintain.