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
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 *