正经学徒,佛系记录,不搞事情
基于上文:https://blog.csdn.net/qq_31748587/article/details/84286411 的项目
普通的neo4j查询路径的cql语法如下:
match l=(m)-[]-(n) return l
neo4j还支持最短路径的查询方式,语法如下:
match l=shortestPath(({name:'Keanu Reeves'})-[*]-({title:"Jerry Maguire"})) return l
对应的springboot项目的工具类 Neo4jUtil 中添加方法 getPathList 对返回的路径进行解析
/**
* cql 路径查询 返回节点和关系
* @param cql 查询语句
* @param nodeList 节点
* @param edgeList 关系
* @return List<Map<String,Object>>
*/
public static <T> void getPathList(String cql, Set<T> nodeList, Set<T> edgeList) {
try {
Session session = driver.session();
StatementResult result = session.run(cql);
List<Record> list = result.list();
for (Record r : list) {
for (String index : r.keys()) {
Path path = r.get(index).asPath();
//节点
Iterable<Node> nodes = path.nodes();
for (Iterator iter = nodes.iterator(); iter.hasNext(); ) {
InternalNode nodeInter = (InternalNode) iter.next();
Map<String, Object> map = new HashMap<>();
//节点上设置的属性
map.putAll(nodeInter.asMap());
//外加一个固定属性
map.put("nodeId", nodeInter.id());
nodeList.add((T) map);
}
//关系
Iterable<Relationship> edges = path.relationships();
for (Iterator iter = edges.iterator(); iter.hasNext(); ) {
InternalRelationship relationInter = (InternalRelationship) iter.next();
Map<String, Object> map = new HashMap<>();
map.putAll(relationInter.asMap());
//关系上设置的属性
map.put("edgeId", relationInter.id());
map.put("edgeFrom", relationInter.startNodeId());
map.put("edgeTo", relationInter.endNodeId());
edgeList.add((T) map);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
调用方法:
@GetMapping("getPath")
public Map<String, Object> getPath(){
Map<String, Object> retMap = new HashMap<>();
//cql语句
String cql = "match l=(m)-[]-(n) return l";
//待返回的值,与cql return后的值顺序对应
Set<Map<String ,Object>> nodeList = new HashSet<>();
Set<Map<String ,Object>> edgeList = new HashSet<>();
neo4jUtil.getPathList(cql,nodeList,edgeList);
retMap.put("nodeList",nodeList);
retMap.put("edgeList",edgeList);
return retMap;
}
@GetMapping("getShortPath")
public Map<String, Object> getShortPath(){
Map<String, Object> retMap = new HashMap<>();
//cql语句
String cql = "match l=shortestPath(({name:'Keanu Reeves'})-[*]-({title:\"Jerry Maguire\"})) return l";
//待返回的值,与cql return后的值顺序对应
Set<Map<String ,Object>> nodeList = new HashSet<>();
Set<Map<String ,Object>> edgeList = new HashSet<>();
neo4jUtil.getPathList(cql,nodeList,edgeList);
retMap.put("nodeList",nodeList);
retMap.put("edgeList",edgeList);
return retMap;
}
结果:
项目地址:
http://note.youdao.com/noteshare?id=9da90834156c95d23a6f80e3a28ba623