Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing parent child mapping in memory. To list all reachable child for a parent efficiently

I have parent and child mappings in reational database as below,

relationship_id | parent_id | child_id
1               | 100009    | 600009
2               | 100009    | 600010
3               | 600010    | 100008

for performance optimization, i like to keep all these mappings in memory. Here, a child will be having more than one parent and a parent has more than 2 children. I guess, i should use "Graph" data structure.

Populating into memory is a one time activity. My concern is that, when I ask to list all child (not only immediate child) it should return them as fast as possible. Addition and deletion happens rarely. What data structure and algorithm I should use?

Tried MultiHashMap, to achieve O(1) search time, but it has more redundancy.

like image 964
krishna Avatar asked Feb 22 '13 12:02

krishna


1 Answers

Have a graph data structure for parent-child relationships. Each GraphNode can just have an ArrayList of children.

Then have HashMap that maps ID to GraphNode.

You need to figure something out so you don't create a cycle (if this is possible) which will cause an infinite loop.

like image 154
Bernhard Barker Avatar answered Oct 24 '22 01:10

Bernhard Barker