Search code examples
neo4jcyphergrandstack

Neo4j Recursive function


I am trying to make a tag system using Neo4j Cypher and having a very hard time (spent the last twelve hours banging my head) to making a recursive function.

Let's say an array of property is given.

The recursive function will: 1. first check if the root has a node relationship [:b] with a node that has property 'name' value as the first element in the array.

a. If yes, simply set the root to the next element and check if the next node has property 'name value as the second element in the array

b. Else, create a new node with the property and set that node as the root.


Solution

  • This query will make sure that the names in the names parameter (a list of strings) are represented by Name nodes linked together, in order, by b relationships:

    MERGE (first:Name {name: $names[0]})
    FOREACH(i IN RANGE(1, SIZE($names)-1) |
      MERGE (a:Name {name: $names[i-1]})
      MERGE (c:Name {name: $names[i]})
      MERGE (a)-[:b]->(c)
    )
    

    The first MERGE is there so that a names list with only one element will still cause a single node to be created (if necessary).

    For example, if the names parameter is ['aa','bb','cc'], then the resulting path will look like this:

    enter image description here