'Binding end node of known path to variable to use for CRUD operations

I'm relatively new to neo4j and I'm not quite sure how to do more complex queries. I want to build a graph which in part is analogous to a file tree structure (but with some extra connections and special things happening at the leafs). Each node has a unique path in the file-like tree and the application code will have access to that node-path-id and perform CRUD operations on the node. For this reason, I would like to know what the best way of getting an identifier for the node that the node-path-id identifies in cypher.

You could obviously store the entire path in the node and search for the id as you normally would but that feels unnecessary when the path is already in the graph. The only way of utilizing this that I could figure out is by generating the query below dynamically. This creates lots of useless identifiers though (if scaled up). Is there a better way to localize a node when a path to it is already known?

Also, as the special root node will be accessed for each query I will want to make sure that the database can access it without searching the entire graph for it. How do you do that. Is it enough to give it a unique :root label for instance?

MATCH (:root)-[:child]->(A)
WHERE A.name = "myDir"
MATCH (A)-[:child]->(B)
WHERE B.name = "nestedDir"
MATCH (B)-[:child]->(C)
WHERE C.name = "deepDir"
CREATE (:leafNode {name:"myLeaf"})<-[:child]-(C) // or some other CRUD operation utilizing C node. 

Other attempts: apoc.path.subgraphNodes doesn't allow filtering on properties. Is pretty close to what I want to do though. Using UNWIND is pretty complex and I couldn't find a solution.



Solution 1:[1]

The best way to do this in Neo4J would probably be variable length patterns. Assuming that your data is a directed acyclic graph of structure and you want to fetch the path for the node with name myDir you could do this

MATCH (node:Node) WHERE node.name = "myDir"
MATCH path=(:root)-[:child*]->(node)
RETURN reduce(s="", node IN nodes(path) | node.name + "/")

For your question regarding easily finding the root then giving it a unique label is a good solution.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Simon Thordal