首页 > 解决方案 > Cypher - how to walk graph while computing

问题描述

I'm just starting studying Cypher here.. How would would I specify a Cypher query to return the node connected, from 1 to 3 hops away of the initial node, which has the highest average of weights in the path?

Example

Graph is: (I know I'm not using the Cypher's notation here..)

A-[2]-B-[4]-C
A-[3.5]-D

It would return D, because 3.5 > (2+4)/2

And with Graph:

A-[2]-B-[4]-C
A-[3.5]-D
A-[2]-B-[4]-C-[20]-E
A-[2]-B-[4]-C-[20]-E-[80]-F

It would return E, because (2+4+20)/3 > 3.5 and F is more than 3 hops away

标签: neo4jcypher

解决方案


1) 要选择长度从 1 到 3 的可能路径 - 使用 match with variable length relationships

MATCH p = (A)-[*1..3]->(T)

2) 然后用reduce function计算平均重量。然后排序和限制得到一个值:

MATCH p = (A)-[*1..3]->(T)
WITH p, T, 
     reduce(s=0, r in rels(p) | s + r.weight)/length(p) AS weight
RETURN T ORDER BY weight DESC LIMIT 1

推荐阅读