Create relationship from first node to last node in a path

I know if I knew how to do this I would consider this super easy, but I am stuck. I tried using the startnode and endnode on a path but..
Let's say I have ten nodes connected with a "goesTo" relationship. All I want to do is create a New "shortcut" relationship between the First Node and the Last Node. Can someone be kind enough post this 4 or five lines of cypher to do this? thanks for helping me break this mental block.. :) Thanks Guys!

So you've got something like this:

CREATE (a:Foo {name: "a"})-[:GOES_TO]->(b:Foo{name: "b"})-[:GOES_TO]->(c:Foo {name:"c"})-[:GOES_TO]->(d:Foo {name:"d"}) RETURN *

And you want to create a relationship between a and d? How about this:

// Find all paths using variable length path operator
MATCH p=(begin:Foo)-[*]->(end:Foo)

// Get the longest path
WITH p, size(nodes(p)) AS length
WITH p ORDER BY length DESC LIMIT 1

// Get all nodes in the path
WITH nodes(p) AS pathNodes

// Get the first and last nodes in the path
WITH pathNodes[0] AS begin, pathNodes[-1] as end

// Create shortcut relationship
CREATE (begin)-[:SHORTCUT]->(end)

Instead of matching on all paths and looking for the longest, could also add predicates to exclude nodes with any incoming/outgoing relationships to identify the beginning and ending nodes:

// Identify the beginning and ending nodes as those without any incoming (begin)
// or outgoing (end) paths
MATCH p=(begin:Foo)-[:GOES_TO*]->(end:Foo) WHERE NOT EXISTS {
 WITH end
 MATCH (end)-[:GOES_TO]->()
} AND NOT EXISTS {
 WITH begin
 MATCH ()-[:GOES_TO]->(begin)
}


// Get all nodes in the path
WITH nodes(p) AS pathNodes

// Get the first and last nodes in the path
WITH pathNodes[0] AS begin, pathNodes[-1] as end

// Create shortcut relationship
CREATE (begin)-[:SHORTCUT]->(end)
2 Likes

Thank You SO Much.. I will try this out TODAY!.. Its for a core project so this is a huge help for us.. I have to add two or three relationship types into the pathway but I think that is no big deal.. :) I will work on this today sir..
Thanks Bill..

1 Like

works great.. thanks Boss.. .. thanks man

1 Like