
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…
- In the Var section, click + to add a new variable, set the name to
paymentTotal
and Type tofloat
, as shown in the following screenshot: - Insert the following code into the expression field:
customer.payment1+customer.payment2+customer.payment3+customer.payment4+customer.payment5+customer.payment6
- Repeat step 1 for a variable named
averageLastSixMonths
with Type set tofloat
, and a variable namedaverageAnnual
also with Type set tofloat
. - Select
paymentTotalRow
by clicking the left mouse button. - Drag the
paymentTotalRow
variable into the Expression column for the new variableaverageLastSixMonths
. - Add
/6
to the end of the expression to get:Var.paymentTotal / 6
- Drag the input column
annualTotal
into the Expression column for the variableaverageAnnual
and add/12
to the end of the expression. - Add a final
float
variable calledvariance
. - Drag in the variable
averageLastSixMonths
add–
(minus) then drag in the variableaverageAnnual
. - Highlight all the four columns using the Shift and right mouse click method and add them to the end of the output table.
- Your
tMap
should now look like the following screenshot: - 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.