You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

RedisGraph技术咨询:如何导入路径数据并查询最短路径?

RedisGraph 导入与最短路径查询实现

1. 导入路径数据

将你的路径数据转化为RedisGraph可执行的Cypher语句,通过MERGE操作避免重复创建节点和边:

// 创建所有位置节点
MERGE (e:Location {name: 'Entry'})
MERGE (r:Location {name: 'Reception'})
MERGE (c:Location {name: 'Corner'})
MERGE (ex:Location {name: 'Exit'})
MERGE (g:Location {name: 'Gate'})
MERGE (ll:Location {name: 'LiftLobby'})

// 创建带距离属性的连接边
MERGE (e)-[:CONNECTS {distance: 152}]->(r)
MERGE (r)-[:CONNECTS {distance: 176}]->(c)
MERGE (r)-[:CONNECTS {distance: 153}]->(ex)
MERGE (c)-[:CONNECTS {distance: 41}]->(g)
MERGE (c)-[:CONNECTS {distance: 176}]->(r)
MERGE (g)-[:CONNECTS {distance: 53}]->(ll)
MERGE (g)-[:CONNECTS {distance: 41}]->(c)
MERGE (ll)-[:CONNECTS {distance: 53}]->(g)

关键说明

  • 所有节点统一标记为Location标签,用name属性存储节点标识
  • 边使用CONNECTS关系类型,distance属性存储两点间的距离单位
  • MERGE关键字会自动校验节点/边是否已存在,无需担心重复插入问题

2. 查询两点间的最短路径

提供两种常用的最短路径查询方式,按需选择:

方式1:使用内置最短路径算法(权重优先)

MATCH (start:Location {name: 'Entry'}), (end:Location {name: 'LiftLobby'})
CALL algo.shortestPath(start, end, 'CONNECTS', 'distance')
YIELD path, weight
RETURN path, weight AS total_distance

方式2:手动匹配路径并计算最短距离

MATCH p = (start:Location {name: 'Entry'})-[*]->(end:Location {name: 'LiftLobby'})
WITH p, reduce(total = 0, edge IN relationships(p) | total + edge.distance) AS total_distance
ORDER BY total_distance ASC
LIMIT 1
RETURN p AS shortest_path, total_distance

关键说明

  • 修改start和end的name属性值,即可查询任意两点间的最短路径
  • 方式1调用RedisGraph内置算法,执行效率更高;方式2适合需要自定义路径过滤逻辑的场景

内容的提问来源于stack exchange,提问作者Mohit H

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 21:55:27