'Create relationship between nodes created from UNWIND list

I am passing into a Cypher query a List<Map<String, Object>>, which I am using to create a series of nodes based on the key-value pairs contained in the Map<String, Object>.

I now want to be able to link those nodes together, in the order they were unwound.

Current cypher/java code:

public static void doMergeAndLink(List<Map<String, Object>> nodeProperties)
{
    try (Session session = driver.session())    
    {
        session.run("UNWIND $nodeProperties AS np " +
            "MERGE (n:Event {name:np.name, location: np.location, eventDate:np.eventDate}) "
        , parameters("nodeProperties",nodeProperties));
    }
    catch(Exception e){}
}

What I want now is to be able to add MERGE (n)-[:NEXT_EVENT]->(n+1) but I don't know the Cypher to do that



Solution 1:[1]

You can use UNWIND to create a linked nodes. First create the nodes for your nodeProperties list then create the NEXT_EVENT relationship.

Below query will create a node1 linked to node2 in your list $nodeProperties. UNWIND will create another list of index numbers from 0 to end (except the last item). Then merge (or match if it exists) the node based on the name (assuming your node primary key is name). Then create the needed relationship :NEXT_EVENT. Unwind is like a FOR LOOP so it will link item1 to item2 then item2 to item3 ... until item99 to item100.

 WITH $nodeProperties AS np 
 UNWIND range(0, size(np) - 2) as idx
 MERGE (node1:Event {name:np[idx].name, location: np[idx].location, eventDate:np[idx].eventDate})
 MERGE (node2:Event {name:np[idx+1].name, location: np[idx+1].location, eventDate:np[idx+1].eventDate})
 CREATE (node1)-[:NEXT_EVENT]->(node2)

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