cancel
Showing results for 
Search instead for 
Did you mean: 

How do I exclude paths that return to the start node?

graphene
Node Link

I have a query that is returning more paths than it needs to because it will go from the start node to other nodes, then back through the start node again 

Here are some of the paths it returns:

1-3 
1-3-2 
1-4
1-3-2-1-4 
The last path is unnecessary. If I can get from 1-4 directly, I don't care if I can also get there by adding a bunch of other hops and coming back to 1 to go directly to 4. 
 
How do I exclude paths that return to the start node?
 
Generate the sample data I'm playing with:
CREATE (n3:Test {appId: 3})<-[:MEDIUM]-(n0:START:Test {appId: 1})-[:WEAK]->(:Test {appId: 2})-[:STRONG]->(n3),
(n0)-[:STRONG]->(:Test {appId: 4})-[:STRONG]->(n4:Test {appId: 5})-[:WEAK]->(:Test {appId: 6})-[:MEDIUM]->(:Test {appId: 8}),
(n4)-[:MEDIUM]->(n11:Test {appId: 7})-[:STRONG]->(:Test {appId: 9}),
(n11)-[:WEAK]->(:Test {appId: 10})
 here's the query I'm running:
MATCH(n:Test {appId: 1})
MATCH p=(n)-[*]-(m)
WHERE NOT m.appId = 1
WITH m, relationships(p) AS rels
WITH m, 
any(r IN rels WHERE type(r) = 'MEDIUM') AS medium,
any(r IN rels WHERE type(r) = 'WEAK') AS weak
WITH m, CASE
  WHEN weak THEN "WEAK"
  WHEN medium AND NOT weak THEN "MEDIUM"
  WHEN NOT medium AND NOT weak THEN "STRONG"
END AS weight
RETURN collect(m.appId), weight
 
 
1 REPLY 1

glilienfield
Ninja
Ninja

Try this. It selects only paths where the path nodes includes the 'n' node only once. Note, I also added the 'distinct' clause to your collect, as the list had duplicates. 

MATCH(n:Test {appId: 1})
MATCH p=(n)-[*]-(m)
WHERE single(i in nodes(p) where id(i) = id(n))
WITH m, relationships(p) AS rels
WITH m, 
any(r IN rels WHERE type(r) = 'MEDIUM') AS medium,
any(r IN rels WHERE type(r) = 'WEAK') AS weak
WITH m, CASE
  WHEN weak THEN "WEAK"
  WHEN medium AND NOT weak THEN "MEDIUM"
  WHEN NOT medium AND NOT weak THEN "STRONG"
END AS weight
RETURN collect(distinct m.appId), weight