In the post titled, , we looked at how we can unnest / flatten a path in Graph using GQL. In this post we will look at the how to identify each match when there are multiple paths . Let’s start with our basic Social Network example.

We are interested in path(s) from Saqib to Uroosa. Notice that are two paths for that 1) Saqib -> Angela -> Scott -> Uroosa; 2) Saqib -> Fatima -> Eleni -> Uroosa. We are also interested in the exact nature of the relationship i.e. co-worker vs. friend.
Let’s start by create a Graph that represents that above relationships
create graph social_graph{
node person ({name string})
, edge relationship (person)-[{type string}]->(person)
};
use social_graph;
INSERT (n1:person {_id:'saqib', name:"Saqib"})
, (n2:person {_id:'angela', name:"Angela"})
, (n3:person {_id:'scott', name:"Scott"})
, (n4:person {_id:'uroosa', name:"Uroosa"})
, (n5:person {_id:'fatima', name:"Fatima"})
, (n6:person {_id:'eleni', name:"Eleni"})
, (n1)-[link1:relationship {type:"friend"}]->(n2)
, (n2)-[link2:relationship {type:"co-worker"}]->(n3)
, (n3)-[link3:relationship {type:"friend"}]->(n4)
, (n1)-[link4:relationship {type:"co-worker"}]->(n5)
, (n5)-[link5:relationship {type:"friend"}]->(n6)
, (n6)-[link6:relationship {type:"friend"}]->(n4)
Next use the pnodes function to get the two possible PATH(s) as JSON
use social_graph;
MATCH path = all SHORTEST (a {_id:'saqib'})-[links]->{1,4}(b {_id:'uroosa'})
return pnodes(path);
This will output:
------------ path 1
[{"schema":"person","id":"saqib","uuid":"11024814086826229762","values":{"name":"Saqib"}},{"schema":"person","id":"angela","uuid":"7205761602816049155","values":{"name":"Angela"}},{"schema":"person","id":"scott","uuid":"2666133178426589188","values":{"name":"Scott"}},{"schema":"person","id":"uroosa","uuid":"14771808976798482437","values":{"name":"Uroosa"}}]
------------ path 2
[{"schema":"person","id":"saqib","uuid":"11024814086826229762","values":{"name":"Saqib"}},{"schema":"person","id":"fatima","uuid":"6413128068398841862","values":{"name":"Fatima"}},{"schema":"person","id":"eleni","uuid":"9583662206067671047","values":{"name":"Eleni"}},{"schema":"person","id":"uroosa","uuid":"14771808976798482437","values":{"name":"Uroosa"}}]Now let’s see look at how to get the each hop as row and also get the relationship type:
MATCH path = all SHORTEST (a {_id:'saqib'})-[links]->{1,}(b {_id:'uroosa'})
for link in links WITH ORDINALITY hop_number
return table(link._from, link._to, link.type, hop_number, pnodeIds(path), PATH_LENGTH(path));
This will output:

Notice that the output contains two possible paths. pnodeIds are Path Identifiers. hop_number indicates the ordinal hop number in the path.
Leave a Reply