Create relationship between nodes created from UNWIND list

696 Views Asked by At

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

2

There are 2 best solutions below

2
On BEST ANSWER

Using apoc.coll.pairsMin you can extract pairs of adjacent node properties: https://neo4j.com/labs/apoc/4.0/data-structures/collection-list-functions/

So in their example,

apoc.coll.pairsMin([1,2,3]) YIELD value

returns:

[[1,2],[2,3]]

So to put it into practice and link adjacent pairs of nodes created from a list of maps, I created a list similar to your $nodeProperties, and linked them:

WITH [{a: "foo0", b: "bar0"}, {a: "foo1", b: "bar1"}, {a: "foo2", b: "bar2"}] as allNodes
WITH apoc.coll.pairsMin(allNodes) as nodePairs
UNWIND nodePairs as pair
MERGE (n0:Foo {name: pair[0].a, prop: pair[0].b})
MERGE (n1:Foo {name: pair[1].a, prop: pair[1].b})
MERGE (n0)-[:RELATION]-(n1)
RETURN *

Nodes linked together

2
On

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)