限制Neo4j apoc.path.expand by relationship属性值
在加权Neo4j图中,是否有可能找到给定节点的n个跃点内的所有路径,并且限制仅返回/进一步扩展每个节点的前m个关系(按权重) 例如,给定以下图表: 此查询限制Neo4j apoc.path.expand by relationship属性值,neo4j,cypher,neo4j-apoc,Neo4j,Cypher,Neo4j Apoc,在加权Neo4j图中,是否有可能找到给定节点的n个跃点内的所有路径,并且限制仅返回/进一步扩展每个节点的前m个关系(按权重) 例如,给定以下图表: 此查询 MATCH (n0:Foo {n: "a"}) CALL apoc.path.expand(n0, "TO>", "", 1, 3) YIELD path as p WHERE ALL (x in relationships(p) where x.score > 0.0
MATCH (n0:Foo {n: "a"})
CALL apoc.path.expand(n0, "TO>", "", 1, 3)
YIELD path as p
WHERE ALL (x in relationships(p) where x.score > 0.02) // Additional constraint not directly related to the question
RETURN p, length(p) AS hops
ORDER BY hops
。。。返回:
╒═══════════════════════════════════════════════════════════════════════╤══════╕
│"p" │"hops"│
╞═══════════════════════════════════════════════════════════════════════╪══════╡
│[{"n":"a"},{"score":0.03},{"n":"d"}] │1 │
├───────────────────────────────────────────────────────────────────────┼──────┤
│[{"n":"a"},{"score":0.03},{"n":"d"},{"n":"d"},{"score":0.11},{"n":"k"}]│2 │
├───────────────────────────────────────────────────────────────────────┼──────┤
│[{"n":"a"},{"score":0.03},{"n":"d"},{"n":"d"},{"score":0.1},{"n":"j"}] │2 │
├───────────────────────────────────────────────────────────────────────┼──────┤
│[{"n":"a"},{"score":0.03},{"n":"d"},{"n":"d"},{"score":0.12},{"n":"l"}]│2 │
└───────────────────────────────────────────────────────────────────────┴──────┘
是否也可以将每个节点的传出关系限制在前2名,例如,按分数
预期产出将是:
╒═══════════════════════════════════════════════════════════════════════╤══════╕
│"p" │"hops"│
╞═══════════════════════════════════════════════════════════════════════╪══════╡
│[{"n":"a"},{"score":0.03},{"n":"d"}] │1 │
├───────────────────────────────────────────────────────────────────────┼──────┤
│[{"n":"a"},{"score":0.03},{"n":"d"},{"n":"d"},{"score":0.11},{"n":"k"}]│2 │
├───────────────────────────────────────────────────────────────────────┼──────┤
│[{"n":"a"},{"score":0.03},{"n":"d"},{"n":"d"},{"score":0.12},{"n":"l"}]│2 │
└───────────────────────────────────────────────────────────────────────┴──────┘
我认为你不可能一次就做到这一点,因为你必须对每一条道路上的每一步进行比较 另外,你必须考虑这样的情况,你的分数是0.09,0.11,0.11,0,12 其中,取前2名可能返回任意结果
MATCH p=(n0)-[:TO*1..3]->()
// From starting node
WHERE n0.n='a'
// get for each node the scores of the outgoing reps, sort them and get the second one
// and put them in an array
WITH p,
REDUCE (array=[], n IN [x in nodes(p) WHERE (x)-[:TO]->()] |
(array
+ apoc.coll.sort([(n)-[r:TO]->() | r.score])[1])
) AS cutOffScoresByStep
WITH p,cutOffScoresByStep
// only get the paths where the score on each rel is higher than the corresponding cutOffScore
WHERE ALL (rel IN relationships(p)
WHERE rel.score >= cutOffScoresByStep[apoc.coll.indexOf(relationships(p),rel)]
)
RETURN p
谢谢你的帮助。在缩减步骤中,我在叶节点(即没有
:TO
关系的节点)上遇到了一个问题,该解决方案会为r.score
返回null,而减少该值将导致数组
为null。我编辑了您的原始答案,以便在REDUCE
函数列表表达式中包含WHERE
子句。我还添加了一个开始节点,并在最后的WHERE ALL
子句中反转比较,以匹配我的原始问题。再次感谢!