Combining depth and width traversals in a single cypher request

My graph is a tree structure with root and end nodes and a row of nodes between them with relations [:NEXT]->from one to another. Some nodes along this path also relate [:BRANCH]->to other root nodes, and through them to other rows of nodes.

Which Cypher query will return an ordered list of nodes from start to finish, and will any relationships BRANCHbe included in the entries for nodes that have them?

EDIT: This is not a technical diagram, but the basic structure is as follows:

enter image description here

with each node depicted as a black circle. In this case, I would like each node to be displayed here.

+4
3

MATCH p=(root)-[:NEXT*0..]->(leaf)
OPTIONAL MATCH (leaf)-[:BRANCH]->(branched)
RETURN leaf, branched, length(p) as l
ORDER BY l ASC

. : http://gist.neo4j.org/?9042990

+6

- - ( ):

START n=node(startID), child=node(*)
MATCH (n)-[rels*]-(child)
WHERE all(r in rels WHERE type(r) IN ["NEXT", "BRANCH"])
RETURN *

Neo4j 2.0.x Cypher.
, startID: , , . - [rels*1..n] - ...

+1

, , , , , , Cypher.

MATCH p =(n)-[:NEXT*]->(end) 
WITH collect(p) as node_paths
MATCH (n1)-[:NEXT]->(m)-[:BRANCH]->(n2)
WITH collect(m) as branch_nodes , node_paths
RETURN branch_nodes,node_paths

Now node_pathsconsists of all the paths with the template (node)-[:NEXT]->(node)-[:NEXT]->...(node). Now you have the paths and nodes of the branches (the starting point of basically all the paths in node_paths, except the one that appears from the rootnode), you can arrange the output order accordingly.

+1
source

Source: https://habr.com/ru/post/1526298/


All Articles