我有Neo4j社区3.5.5,在这里建立了一个图形数据模型,其中包含火车站和火车站之间的线段。站和线段是节点,connect是链接它们的关系。
我想命名一个起点站和一个终点站,并总结两者之间所有铁路路段的长度。我在下面尝试了Cypher查询,但Neo4j无法将line_section
识别为节点类型。
match (n1:Station)-[:Connect]-(n2:Station)
where n1.Name='Station1' and n2.Name='Station3'
return sum(Line_Section.length)
我知道可以使用Neo4j Traversal API进行求和。可以在Cypher中做到这一点吗?
答案 0 :(得分:1)
首先在变量中capture
从起始节点到结束节点的路径,然后在变量上reduce
的length属性。
MATCH path=(n1: Station { name: 'Station1' })-[:Connect]->(n2: Station { name: 'Station2' })
RETURN REDUCE (totalLength = 0, node in nodes(path) | totalLength + node.length) as totalDistance
答案 1 :(得分:0)
假设线段节点的标签为Line_Section
,则可以使用variable-length relationship模式来获取整个路径,list comprehension来获得线段节点的列表,{{ 3}}来获取各个节点,然后使用UNWIND来SUM
所有线段长度:
MATCH p = (n1:Station)-[:Connect*]-(n2:Station)
WHERE n1.Name='Station1' AND n2.Name='Station3'
UNWIND [n IN NODES(p) WHERE 'Line_Section' in LABELS(n)] AS ls
RETURN p, SUM(ls.length) AS distance
或者,您可以使用REDUCE
代替UNWIND
和SUM
:
MATCH p = (n1:Station)-[:Connect*]-(n2:Station)
WHERE n1.Name='Station1' AND n2.Name='Station3'
RETURN p, REDUCE(s = 0, ls IN [n IN NODES(p) WHERE 'Line_Section' in LABELS(n)] |
s + ls.length) AS distance
[已更新]
Note: a variable-length relationship with an unbounded number of hops is expensive, and can take a long time or run out of memory.
If you only want the distance for the shortest path, then this should be faster:
MATCH
(n1:Station { name: 'Station1' }),
(n2:Station {name: 'Station3' }),
p = shortestPath((n1)-[*]-(n2))
WHERE ALL(r IN RELATIONSHIPS(p) WHERE TYPE(r) = 'Connect')
RETURN p, REDUCE(s = 0, ls IN [n IN NODES(p) WHERE 'Line_Section' in LABELS(n)] |
s + ls.length) AS distance