【问题标题】:Adding relationships between an array of array of objects in Neo4j Cypher在 Neo4j Cypher 中添加对象数组之间的关系
【发布时间】:2021-09-14 22:35:06
【问题描述】:

我有三个对象数组,如下所示:

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"
  }
]

在它们之间添加关系的最佳方式是什么?请注意,数组的长度相同。

我需要一个 Cypher 查询,它可以遍历从 0 到 orgs.length 的范围,并在 i 处添加每个元素之间的对应关系。例如 org[i]、contacts[i]、location[i]

我尝试了以下方法,但它给了我一个爆炸性的组合,其中第一个组织映射到位置数组和联系人数组中的所有条目,而我想要的是一对一映射。

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})
    )

任何帮助将不胜感激。提前致谢。

【问题讨论】:

    标签: neo4j cypher


    【解决方案1】:

    我认为您不需要 UNWIND 所有数组

    WITH $orgs AS orgs,
         $locs AS locs,
         $contacts AS contacts
    
    UNWIND $orgs as orgs
    
    
    FOREACH (i IN range(0, size(orgs) - 1) |
        MERGE (org:Organization { id: orgs[i].id })
        MERGE (loc:Location {id: locs[i].id})
        MERGE (contact:Contact {id: contacts[i].id})
        MERGE (org)-[:LOCATED_AT]->(loc)
        MERGE (org)-[:CONTACT_AT]->(contact)
    )
    

    应该这样做

    【讨论】:

      【解决方案2】:

      解决方案已发布在 Neo4j 官方网站上。我也在这里分享。

      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})
      

      链接到原始answer

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-04-06
        • 1970-01-01
        • 2013-02-06
        • 2019-02-01
        相关资源
        最近更新 更多