CI relationships multilevel downstream in a list

saksham2
Kilo Contributor

Suppose we have a CI X

Its parents are P,Q and children are Y,Z

Now Y has children C and D and Z has children E and F.

I have to get all child CI's ( Y,Z,C,D,E, F) in a single list.

I am using the code (sample)

var childlist = [] ;

var prel = new GlideRecord ('cmdb_rel_ci');

prel.addQuery('parent',current.cmdb_ci);

prel.query();

while (prel.next())

{

gs.print ("list is" +prel.parent);

childlist.push(prel.child.toString());

}

But I get only 1 level downstream Ci   (ie, CI   Y and Z ,the children for current Ci X )from this.

How do I get the 2nd level downstream Cis and the subsequent levels for X ( ie   C,D,E,F)

?

6 REPLIES 6

Sebastian R_
Kilo Sage

Right now you are querying for the direct children of X, but you want to have all children and their children (it ´s like traversing a tree: see therefore e.g. Tree traversal - Wikipedia )



If you only need 2 levels you can do it with a second while-loop.



var prel = new GlideRecord ('cmdb_rel_ci');


prel.addQuery('parent',current.cmdb_ci);


prel.query();


while (prel.next())


{


gs.print ("list is" +prel.parent);


childlist.push(prel.child.toString());



/* Second Level */


var prel2 = new GlideRecord ('cmdb_rel_ci');


prel2.addQuery('parent',prel.cmdb_ci);


prel2.query();


while (prel2.next())


{


gs.print ("list is" +prel2.parent);


childlist.push(prel2.child.toString());


}


/* End of second Level*/



}



If you need all children and their children etc. you can use something like Depth-first search and traverse each node recursively until they have no child left. (Keep in mind that you can have more than two children).


Hi Sebastian,



The point here i that we need all downstream and upstream CI's for a CI in a list and there is no limit for it.


Even if we somehow get all the CI's it would cause performance issue and take more time to run the query as a part of the script.



I am looking for some way to get the Ci list without repeating the queries made at each level.



Thanks,
Saksham


If you want to get all upstream and downstream CIs of your current CI, you can do somethin like this:



var prel = new GlideRecord ('cmdb_rel_ci');


var qr = prel.addQuery('parent',current.cmdb_ci);


qr.addOrCondition('child', current.cmdb_ci);


prel.query();  



If you want to have fewer querys you can later query for all CIs you need to traverse.


Therefore you can use two lists. The first list is your result with all CI and the second list contains all elements for which you have to query their parents/childs.



I can ´t see a simple solution for your task. Even from a plain database view you would need a recursive query.


Did got solution for this?