Neo4j cypher - 过滤掉子节点

时间:2017-12-08 15:05:28

标签: neo4j cypher

想象一下下面的图表:

enter image description here

目标是查询两个实体之间的所有连接节点(&#34; Main&#34;&#34; Other&#34;在这种情况下),但过滤掉相互后代。换句话说,我希望结果集只包含 a b ,但 < em> not c ,因为C是B的后代,已经包含在结果集中。

3 个答案:

答案 0 :(得分:1)

我使用此示例数据集重现了您的场景:

Sample data set

此查询应该有效:

// match common child nodes between 'main' and 'other'
MATCH (:Node {name : "Main"})-[:child]->(child:Node)<-[:child]-(:Node {name : "Other"})
// match the children of child when exists
OPTIONAL MATCH (child)-[:child]->(n:Node)
// store children and childrenOfChild in separeted arrays
WITH collect(child) as children, collect(n) as childrenOfChild
// filter ...
WITH filter(child in children WHERE NOT child IN childrenOfChild) as directChildren
UNWIND directChildren as directChild
// return only direct child
RETURN directChild

输出:

╒═════════════╕
│"directChild"│
╞═════════════╡
│{"name":"b"} │
├─────────────┤
│{"name":"a"} │
└─────────────┘

答案 1 :(得分:0)

如果我正确理解了问题的条件,那么你需要找到这样的子节点,从原始节点中获取这些节点的唯一方法是:

MATCH p = (Main:Node {id: 'main'})
          -[:child*]->(T:Node)<-[:child*]-
          (Other:Node {id: 'other'})
WITH T, 
     collect(p) as pw WHERE size(pw) = 1
RETURN T

答案 2 :(得分:0)

此查询收集2个实体的所有直接后代,然后筛选出具有直接后代作为父实体的实体:

MATCH (:Node {name : "Main"})-[:child]->(child:Node)<-[:child]-(:Node {name : "Other"})
WITH COLLECT(child) AS children
UNWIND children AS c
MATCH (c)<-[:child]-(parent:Node)
WITH c, children, COLLECT(parent) AS parents
WHERE NONE(p IN parents WHERE p IN children)
RETURN c;