Adding relationships between an array of array of objects


I have three arrays of objects as shown below:

const org = [
     id: "orgId1",
     name: "first organization"
     id: "orgId2",
     name: "second organization"

const location = [
     id: "loc1",
     name: "Texas"
     id: "loc2",
     name: "New York"

const contacts = [
     id: "contact1",
     name: "James"
     id: "contact2",
     name: "John"

What is the optimal way to add relationships between them? Note that the arrays are of the same length.

I need a Cypher query that can loop through a range from 0 to orgs.length, and add corresponding relationships between each element at i. e.g org[i], contacts[i], location[i]

I tried the following, but it gives me an explosive combination where the first org maps to all the entries in location array and contact array, when I want is a one-to-one mapping.

UNWIND $orgs as orgs
UNWIND $locations as locs
UNWIND $contacts as contacts

    FOREACH (i IN range(0, size(orgs) - 1) 
        | MERGE (:Organization { id: orgs[i].id })-[r:LOCATED_AT]->(:Location {id: locs[i].id})
       | MERGE (:Organization { id: orgs[i].id })-[r:CONTACT_AT]->(:Contact {id: contacts[i].id})

Any help would be appreciated. Thanks in advance.

This should work, note that there is only one UNWIND for index (variable i) and the with between the 2 merges, to "activate" the merging mechanism through the variable o :

UNWIND range(0, size($orgs) - 1) as i
with i
MERGE (o:Organization { id: $orgs[i].id })-[r:LOCATED_AT]->(l:Location {id: $locs[i].id}) 
with o, i
MERGE (o)-[r2:CONTACT_AT]->(l2:Contact {id: $contacts[i].id})

With your query, with UNWIND and FOREACH you split the array twice.

1 Like

Worked perfectly. Thanks