试图在嵌套的FOREACH列表中进行MATCH

时间:2016-10-22 16:38:02

标签: neo4j cypher

我有一组标签为Type的节点。其中一些与其他类型节点有关系,而其中一些则没有。我想循环遍历所有Type节点,并根据关系做一些操作(无论是null还是现有关系)

在伪代码中,这就是我想要做的事情:

For each type1 in allTypes
     For each type2 in allTypes
        Match relationship between type1 and type2   
        If relationship between type1 and type2 exists
             do something
        else
             do other thing

但我无法弄清楚如何在Cypher中做到这一点。我知道你不能在Cypher的FOREACH声明中做一个MATCH,所以我正在尝试这样的UNWIND:

MATCH (Types:Type)
WITH COLLECT(Types) AS types
UNWIND types as type1
UNWIND types as type2
MATCH (type1)-[r]->(type2)
RETURN type1.name,type(r), type2.name

这适用于已经存在的所有关系,但是当type1和type2之间没有任何关系时,我的返回结果中没有任何关系。

1 个答案:

答案 0 :(得分:2)

如何使用OPTIONAL MATCH

一些示例数据:

CREATE 
  (t1:Type {name:"t1"}),
  (t2:Type {name:"t2"}),
  (t3:Type {name:"t3"}),
  (t1)-[:REL]->(t2)

查询:

MATCH (t1:Type)
OPTIONAL MATCH (t1)-[r]->(t2:Type)
RETURN
  t1, t2,
  CASE r
    WHEN NULL THEN "other thing"
    ELSE "something"
  END AS info

结果:

╒══════════╤══════════╤═══════════╕
│t1        │t2        │info       │
╞══════════╪══════════╪═══════════╡
│{name: t1}│{name: t2}│something  │
├──────────┼──────────┼───────────┤
│{name: t2}│(null)    │other thing│
├──────────┼──────────┼───────────┤
│{name: t3}│(null)    │other thing│
└──────────┴──────────┴───────────┘