简体   繁体   中英

Neo4j: Query for a path between two nodes in a specific order of relationships and knowing only label of the last node

For example if I have a complex graph having the following labels and relationships:

N1-a->N2-b->N3-c->N4

N2-d-N5-e->N3

etc.

Now, I want to find a path from (:N1{id:'xyz'}) to any node of type N4 using Cypher but I want the relationships to be in the same order ie a,b,c.

Also, if there are no nodes of type N3 connecting to a node of type N4, I would like to return the path until N3

I was wondering if there is a way to do this. Can someone please help? I am new to Neo4j

If you explicitly know the relationships to traverse, then you should be able to do this with Cypher, though your condition to return N3 if there is no N4 may be tricky.

Is the label of N3 known, or do you just want the path as far as it can go? Also if nodes of label N4 are encountered along the path instead of just at the end, do you want those as well, or are you only interested in N4 at the end of the relationship chain?

Also, are you interested in all possible paths found, or do you just need a single path, if it exists?

This query should work if you explicitly know (and can define in the query) the relationships to traverse, and if you only need a single path if it exists, and if you're only interested in a node of label N4 at the end (or the node just before, if there is no N4 at the end):

MATCH p=(:N1{id:'xyz'})-[:a]->()-[:b]->()-[:c*0..1]->(last)
WHERE length(p) = 3 and last:N4 OR length(p) = 2
WITH p
ORDER BY length(p) DESC
LIMIT 1
RETURN p

If the criteria is more complex, you may need APOC path expander procedures for this.

For using APOC path expander, provided you're using one of the APOC releases from Winter 2018 or newer, you can take advantage of the new sequences feature, which lets you define a repeating sequence of node labels and relationship types. In this case we'll limit the repetition with the maxLevel config parameter.

MATCH (start:N1{id:'xyz'})
CALL apoc.path.expandConfig(start, {sequence:'N1, a>, N2, b>, N3, c>, N4', maxLevel:3}) YIELD path
RETURN path
ORDER BY length(path) DESC
LIMIT 1

If you don't care (or don't know) the labels in the path (with the exception of the last label N4), you can use * for the labels, like so:

sequence:'*, a>, *, b>, *, c>, N4'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM