In continuation of my previous blog about dataweave in mule esb, I will be writing today about Filters in dataweave. If you are interested in reading about previous blog’s you can read them here
- The Power of Transformation, Part I: An Introduction to DataWeave
- The Power of Transformation, Part II: Selector Expressions
So, Let’s get started with the filters in dataweave
In dataweave we can chain many different expressions together to form compound expressions while using various kind of operators. Many times there are requirements during our transformation that we want to filter some data before applying next operator. To do this we can use filter operator, filter operator iterates through elements in an array or keys in an object and results in an array that only contains the elements which match the criteria specified by the filter operator.
Let’s take an example of below XML data.
So we want to filter above XML data and only operate on books that have a price above 35.00, we can do this very easily by using filter operator on our transformation.
First I will show you the output without filter operator and then the output with filter operator applied on the transformation.
With Filter operator
Notice the difference in the output, Now the output is being filtered with the books that have their price above 35.00.
Point to note here is the filter condition expressed in the right-hand operand makes reference to $.price. This key is the key that is the output of the map operation of transformation, it not the same that of input, I could have easily named it cost in my map transformation and could have used it instead of price. The example is below take a note of $.cost
The filter operator is being applied to the output produced by the Map operator, Map produces an array that becomes the left-hand operand of the filter operator, which iterates through the array and produces an array of objects filtering out those objects which fail the criteria.
Many times during your transformation you will faces a situation where you only want a type of data in your output if it match’s some kind of criteria, doing this in dataweave is very simple, We call it conditional filtering , since the output is based on some condition.
Taking the same XML in our example above, Suppose we only want the name of author in our output if the book category is of children else we don’t want to give author name in our output data.
Note that I have surround the entire author key:value pair in parentheses. This is the left-hand operand to the when operator. The right-hand operand is a boolean expression. Only when this evaluates to true, is the wind key:value pair included in the output.
These are the two ways you can do filtering in dataweave. I will continue to write about more complex dataweave transformation in my future blogs. Do let me know your thoughts about it.