Lukasmp3
Lukasmp3

Reputation: 148

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 e.g. 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?

Upvotes: 0

Views: 255

Answers (1)

Graphileon
Graphileon

Reputation: 5385

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

Upvotes: 1

Related Questions