I have the following records in a postgres database. The parent_pk is related to the pk in a parent-child relation.
pk name type parent_pk --- ---- ---- --------- 1 hnumber101 house 0 2 hnumber201 house 0 101 dodge_charger vehicle 1 102 mustang vehicle 1 103 civic vehicle 2 301 john user 101 302 edward user 102 303 john user 102 304 john user 103 And I want to generate a json out of the above in the following format- [ { "id": 1, "name": "hnumber101", "type": "house" "child": [ { "id": 101, "name": "dodge charger", "type": "vehicle" "child": [{ "id": 301, "name": "john", "type": "user" }], }, { "id": 102, "name": "mustang", "type": "vehicle" "child": [{ "id": 303, "name": "john", "type": "user" }, { "id": 302, "name": "edward", "type": "user" }], }], }, { "id": 2, "name": "hnumber201", "type": "house" "child": [ { "id": 103, "name": "civic", "type": "vehicle" "child": [{ "id": 304, "name": "john", "type": "user" }], }], }]
I have tried using WITH RECURSIVE query, but that yields the list of entries and then i have to do a lot of looping around/hash maps in my java code to get that child block inside the parent. What would be the most efficient way to do this?