Apache-Nifi: A Short Description of ifElse
Join the DZone community and get the full member experience.
Join For FreeI had been working with Apache-NiFi for last few months at my work. During this period I mostly used csv-based operations.
Recently, I got a problem with the following scenario.
In my flowfile, I needed to do a regex operation on a column value and `replace` them with some other code. I did this easily using the replaceAll function.
First, let's see what replaceAll does in Apache-NiFi. It takes two string arguments, first one is a regex and second is the replacement value.
For more details, I highly recommend reading Apache-NiFi expression language guide on replaceAll.
For the first attempt, I have used the following syntax for my column using UpdateRecord processor :
xxxxxxxxxx
${field.value:replaceAll(${field.value:length():le(8)},'Undefined'):replaceAll('[a-z]+','Wrong')}
This first checks whether the length of the column value is less than 8 characters. If so, it replaces that with Undefined. But some data matched with [a-z]+ pattern had been replaced with Wrong, even though they are less than 8 characters.
I tried to solve this issue myself, and as I was taking too much time, I asked the StackOverflow community. Lamanus’s answer made me think about ifElse in Apache-NiFi.
So now, let's go and see how Apache-NiFi’s ifElse behaves. It takes two arguments, but the difference is that, its the result based on Subject of the expression.
If the subject is true then, first argument is evaluated else second.
As given in the example: ${bool:ifElse('a','b')}, here bool is true. So, if I use replaceAll with this, the value will be replaced with a.
In order to do my scenario using this, I had to change the logic by checking whether it has more than 8 characters and then applying my custom regex based operations.
xxxxxxxxxx
${field.value:length():ge(8):ifElse(
${field.value:replaceAll(‘[a-z]+’,’Wrong’)
:replaceAll('[0-9][a-z]+','Variable1')
,${field.value:replace(${field.value},'Undefined')}
// this is the statement executed when value length is shorter than 8 characters.)}
I hope this short description will give you a better understanding how to use ifElse in Apache-NiFi.
Opinions expressed by DZone contributors are their own.
Comments