如何将查询中的所有节点精确匹配到另一个

时间:2018-08-10 18:54:33

标签: neo4j cypher

我的图形数据库中有2种节点:(Rule)(Constraint)以及1个具有两个属性(Rule)->[:VALIDATED_IF]->(Constraint)的关系{id, type} 所以我的数据库看起来像这样:

(rule1)-[:VALIDATED_IF{id1,type1}]->(constraint1)

我需要确定在关系中是否存在两个完全相同的(rule)和完全相同的(constraint)的不同{id,type}
我该怎么办?

我尝试过类似的事情:

MATCH (r1:Rule)-[p1:VALIDATED_IF]->(c:Constraint)<-[p2:VALIDATED_IF]-(r2:Rule)
WHERE r1.ruleName <> r2.ruleName
AND p1.id = p2.id
AND p2.type = p2.type
RETURN r1.ruleName, r2.ruleName, c.condition

但是给我的规则具有相同的约束之一

2 个答案:

答案 0 :(得分:0)

我们可以汇总每个约束的规则节点,rel id和rel类型,当每个约束有两个以上的:Rule节点时,这也将起作用:

MATCH (rule:Rule)-[rel:VALIDATED_IF]->(c:Constraint)
WITH c, rel.id as relId, rel.type as relType, collect(rule) as rules
WHERE size(rules) > 1
RETURN c.condition as condition, [r in rules | r.ruleName] as rules

在Cypher中,当您聚合时,非聚合变量将成为分组键,因此每行我们将具有约束,rel id和rel类型以及具有相同约束的所有规则rel id以及rel类型。

编辑

好吧,听起来您想获得共享相同约束集合的规则集合。这对您有用吗?

MATCH (rule:Rule)-[rel:VALIDATED_IF]->(c:Constraint)
WITH rule, rel.id as relId, rel.type as relType, c
ORDER BY id(c)
WITH rule, relId, relType, collect(c) as constraints
WITH constraints, collect(rule) as rules
WHERE size(rules) > 1
RETURN [c in constraints | c.condition] as conditions, [r in rules | r.ruleName] as rules

答案 1 :(得分:0)

好的,所以我设法通过改善以下answer来解决:

MATCH (r1:Rule)-[v1:VALIDATED_IF]->(:Constraint)<-[v2:VALIDATED_IF]-(r2:Rule)
WHERE
     v1.id=v2.id AND v1.type = v2.type
MATCH
    (r1)-[:VALIDATED_IF]->(c1:Constraint),
    (r2)-[:VALIDATED_IF]->(c2:Constraint)
WITH
     r1, r2,
     COUNT(DISTINCT c1) AS c1Count, COUNT(DISTINCT c2) AS c2Count
MATCH (r1)-[v1:VALIDATED_IF]->(c:Constraint)<-[v2:VALIDATED_IF]-(r2)
WITH
     r1, r2,
     c1Count, c2Count, COUNT(c) AS commonConstraintsCount, 
     COLLECT(c.condition) AS cond // (5)\n" + 
WHERE
     ID(r1) < ID(r2) AND
     commonConstraintsCount = c1Count AND
     commonConstraintsCount = c2Count AND
     c1Count = c2Count
     RETURN r1.ruleName, r2.ruleName, cond
     ORDER BY r1.ruleName, r2.ruleName

因此,改进之处在于检查公共约束的数量与每个规则具有的约束的数量相同,并检查关系:VALIDATED_IF的属性对于第一个MATCH上的两个节点是否相同