在此示例图中,我想要一个查询,当一对节点在节点对之间定义了多个单跳关系时,将选择不同的单跳路径。我想选择权重最高的单跳关系。
MATCH (x:FooNode) DETACH DELETE x RETURN COUNT(*);
CREATE CONSTRAINT ON (x:FooNode) ASSERT x.name IS UNIQUE;
CREATE (a:FooNode {name: 'a'}), (b:FooNode {name: 'b'}), (c:FooNode {name: 'c'}),
(d:FooNode {name: 'd'}), (e:FooNode {name: 'e'}), (f:FooNode {name: 'f'}),
(a)-[:FooRelation1 {weight: 1}]->(b),
(a)-[:FooRelation2 {weight: 2}]->(b),
(a)-[:FooRelation3 {weight: 3}]->(b),
(a)-[:FooRelation2 {weight: 2}]->(e),
(a)-[:FooRelation4 {weight: 4}]->(e),
(a)-[:FooRelation6 {weight: 6}]->(e),
(e)-[:FooRelation1 {weight: 3}]->(c),
(e)-[:FooRelation2 {weight: 1}]->(f),
(c)-[:FooRelation3 {weight: 3}]->(d);
MATCH p = (s:FooNode) -[r]-> (t:FooNode)
WITH DISTINCT {left: s.name, right: t.name} as Distincts
RETURN Distincts
例如,我想要(a) - [:FooRelation3 {weight:3}] - >(b)返回但不返回(a) - [:FooRelation1 {weight:1}] - >(b) ),(a) - [:FooRelation2 {weight:3}] - >(b)基于权重,所有3个来自(a)到(b)。
想法?
更新
出于某种原因,StackOverflow不会让我发布这个答案,但看起来我找到了一些有用的东西。我仍然希望得到您的反馈。
MATCH p = (n:FooNode)-[r]->(m:FooNode)
WITH DISTINCT n, m, max(r.weight) AS maxw
MATCH p2 = (n2)-[r2]->(m2)
WHERE n2.name = n.name AND m2.name = m.name AND r2.weight = maxw
RETURN p2, type(r2)
从技术上讲,我只需要返回p2。
注意:当您查看图表时,请确保自动完成为OFF;否则Neo4j会自动显示相关的关系(这肯定会让你失望)。
答案 0 :(得分:0)
我们可以通过重用已经在范围内的节点和关系的变量来改进您找到的查询。
MATCH (n:FooNode)-[r]->(m:FooNode)
// no need for distinct since you're using the max() aggregation
WITH n, m, max(r.weight) AS maxw
MATCH p = (n)-[r]->(m)
WHERE r.weight = maxw
RETURN p, type(r)
但是,如果有多个关系具有相同的最大权重,则会返回所有这些关系,而不仅仅是一个。