【问题标题】:How to sum up property value of node type different from starting and ending node with Cypher in Neo4j如何在 Neo4j 中用 Cypher 总结与起始和结束节点不同的节点类型的属性值
【发布时间】:2019-10-28 18:41:00
【问题描述】:

我有 Neo4j 社区 3.5.5,我在其中构建了一个包含火车站和车站之间的线路部分的图形数据模型。车站和线段是节点,连接是连接它们的关系。

我想命名一个起点站和一个终点站,并总结其间所有铁路段的长度。我尝试了下面的 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 中执行此操作?

【问题讨论】:

    标签: neo4j cypher


    【解决方案1】:

    首先capture变量中从开始节点到结束节点的路径,然后reduce它上面的长度属性。

    MATCH path=(n1: Station { name: 'Station1' })-[:Connect]->(n2: Station { name: 'Station2' })
    RETURN REDUCE (totalLength = 0, node in nodes(path) | totalLength + node.length) as totalDistance
    

    【讨论】:

      【解决方案2】:

      假设线段节点有标签Line_Section,您可以使用variable-length relationship 模式获取整个路径,list comprehension 获取线段节点列表,UNWIND 获取单个节点,然后使用aggregationSUM 的所有线段长度:

      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 代替UNWINDSUM

      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
      

      【讨论】:

      • 匹配 p = (n1:Station)-[:Connect*]-(n2:Station) 需要很长时间。 MATCH (n1:Station { name: 'Station1' }),(n2:Station {name: 'Station3' }), p = shortestPath((n1)-[*]-(n2)) 其中所有 (r IN 关系( p) WHERE type(r)= 'Connect') 效果更好。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多