简体   繁体   中英

Neo4j Cypher query: Find node by input path

I have a graph that contains a tree hierarchy of the system. In this graph, one root has indexed label 'MainRoot', all other relationships are type 'hasParent'. I would like to construct a query that would have list of nodes names (=inputPath) as an input and return the node at the end of query.

Now i have this working example, which last returned item is the specified node with the name "java", as I want (located in Root/src/main/java):

// Input
WITH ["Root", "src", "main", "java"] AS inputPath
// Iterator
UNWIND range(0,size(inputPath)-2) AS i
MATCH (parent)<-[:hasParent]-(child)
WHERE (parent.name = inputPath[i]) AND (child.name = inputPath[i+1])
RETURN child

However, I would like to somehow let the query now, that the first parent element of the query is the node with the indexed label 'MainRoot'.

  1. I expect it would be more efficient since it will now, in which node to start the traversal.
  2. If I have structure eg Root/example/Root/src/main/java, the query would also return this 'java' node, which I obviously don't want to return.

Any idea how could I do that?

This is the shortest way I could think of.

WITH ["Root", "src", "main", "java"] AS inputPath     
MATCH path=(mainRoot)<-[:hasParent*]-(child)
WHERE LENGTH(path) = SIZE(inputPath)-1
AND [n IN nodes(path) | n.name] = inputPath
RETURN path

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