cancel
Showing results for 
Search instead for 
Did you mean: 

Head's Up! These forums are read-only. All users and content have migrated. Please join us at community.neo4j.com.

Limit path to first occurance of node with certain label

Assume following graph:

CREATE (a:A {name: 'a'})-[:TO]->(b1:B {name: 'b1'})-[:TO]->(c1:C {name: 'c1'})-[:TO]->(d1:D {name: 'd1'})
CREATE (b1)-[:TO]->(b2:B {name: 'b2'})-[:TO]->(c2:C {name: 'c2'})-[:TO]->(d2:D {name: 'd2'})
CREATE (b2)-[:TO]->(b3:B {name: 'b3'})-[:TO]->(c3:C {name: 'c3'})-[:TO]->(d3:D {name: 'd3'})

Assume, paths are not of fixed length and can get very long.

I would like to retrieve all paths starting in node 'a' but having only the first node labeled 'B'. I also don't want all the subsequent nodes which would have been connected only through one of the nodes labeled with 'B' if it's not the first.

In the example graph, I want this to be the result of my query:

2X_e_ea4657ce4a704ad35fc68d3f86d2daedd8d15fdb.png

I had following idea how to approach this but got stuck on the filtering part of it:

MATCH p = (a:A)-[*]->(t)
WITH labels(t) as ls, a, t
//WHERE path has only first node labeled 'B'
RETURN a, t

Any help would be highly appreciated.

6 REPLIES 6

Hi there, i hope its not too late, did you figure out the solution to this?

In case the individual does not respond, I will try to present a solution. I am going to assume the requirement is to find the paths starting from a specific 'A' node, whose next node is of type 'B', and all remaining nodes along the path are not of type 'B'.  The following query should provide that:

match p=(a:A {name: 'a'})-[:TO]->(:B)-[:TO*0..]->(n)
where none(i in nodes(p)[2..] where i:B)
return a, n, length(p) as length

If this does not answer your question, can your provide you specific requirement?

Hello 

PREVIEW
 
i have attached a screenshot of the graph

glilienfield
Ninja
Ninja

You can try this using pure cypher.  You can also try APOC path methods, where you can specifiy the node labels of terminating nodes in the configuration, which would be the list of labels starting with 'A'

 

match(n:A1{id:0})
match p=(n)-[*]-(m)
with p, nodes(p)[1..-1] as notANodes, nodes(p)[-1] as aNode
where none(x in notANodes where 'A' in [y in labels(x) | substring(y, 0, 1)])
and 'A' in [y in labels(aNode) | substring(y, 0, 1)]
return p

 

Screen Shot 2022-09-20 at 3.43.27 PM.png

Screen Shot 2022-09-20 at 3.43.39 PM.png 

https://neo4j.com/labs/apoc/4.1/overview/apoc.path/

can you please guide me to which APOC procedure are you referring to?,  i have looking for it but wasnt successful to find it yet