Skip to main content
Rizwanul Shaikh 님이 #MuleSoft DataWeave에 질문했습니다

I need to create parent child Hierarchy for which I have written a recursive function but the problem here is it need to create the hierarchy from 11000 records so the Transform message is taking very very long to process that. Can someone please help me with alternate iterative approach or any other setup that help to reduce the API response in seconds.

 

Sample Input:

 

[

{

 "Sub": 0, 

"PG": null,

"PRG": 445 

}, 

{

"Sub": 1,

"PG": 445, 

"PRG": 332 

}, 

{ 

"Sub": 1,

"PG": 332,

"PRG": 666

},

{ 

"Sub": 0, 

"PG": 445, 

"PRG": 334 

}, 

{ 

"Sub": 1,

"PG": 666,

"PRG": 115

},

{

"Sub": 1, 

"PG": 334, 

"PRG": 115 

}

]

 

Expected Output :

[

{

"Sub": 0,

"PG": null,

"PRG": 445,

"children": [

{

"Sub": 1,

"PG": 445,

"PRG": 332,

"children": [

{

"Sub": 1,

"PG": 332,

"PRG": 666,

"children": [

{

"Sub": 1,

"PG": 666,

"PRG": 115,

"children": []

} ] } ]

},

{

"Sub": 0,

"PG": 445,

"PRG": 334,

"children": [

{

"Sub": 1,

"PG": 334,

"PRG": 115,

"children": [ ]

 

} ] } ]

}

]

 

 

Dataweave code I have written with recursion:

 

%dw 2.0

output application/json

 

fun addChild(item, elements) =

item ++ {

"children": (elements filter (child) -> child.PG == item.PRG) map (addChild($, elements))

}

var elements = payload

var roots = elements filter (item) -> item.PG == null

---

roots map (addChild($, elements))

답변 3개
  1. 2023년 7월 30일 오전 4:28

    The below script might help you.

     

    %dw 2.0

    output application/json

    var x = payload groupBy ($.PG default "0")

    fun addChild(item) =

    item ++ {

    "children": x[item.PRG as String] default [] map (addChild($))

    }

    ---

    x."0" map (

    addChild($)

    )