Neo4j使用Cypher和不使用Cypher下的最短路径

[复制链接]
查看11 | 回复3 | 2014-2-19 11:55:14 | 显示全部楼层 |阅读模式
I was looking back at some code I wrote a few months ago to query a neo4j database to find the shortest path between two people via the colleagues relationships that exist.


q1.png (5.78 KB, 下载次数: 7)
下载附件
2013-2-6 09:22 上传

The initial code, written using neography, looked like this:
01.neo = Neography::Rest.new
02.
03.start_node = neo.get_node(start_node_id)
04.destination_node = neo.get_node(destination_node_id)
05.
06.neo.get_paths(start_node,
07.destination_node,
08.{ "type" => "colleagues" },
09.depth = 3,
10.algorithm = "shortestPath")复制代码

The neography code eventually makes a POST request to /node/{start_id}/paths and provides a JSON payload containing the other information about the query.


回复

使用道具 举报

千问 | 2014-2-19 11:55:14 | 显示全部楼层
It works fine and is pretty readable but since I wrote it I’ve learnt how to write queries using the cypher query language so I thought it would be interesting to contrast the two bits of code against each other.
This is the equivalent written using cypher:1.query ="START source=node(#{start_node_id}), destination=node(#{destination_node_id})"
2.query destination)"
3.query 复制代码The amount of lines of code is pretty similar but the thing I like about cypher is that it feels much more declarative and therefore, I think at least, easier to understand.

回复

使用道具 举报

千问 | 2014-2-19 11:55:14 | 显示全部楼层
Having said that, the learning curve for the non-cypher API is a bit easier and it’s probably best to start with that to get a feel of what sorts of things you can do with a graph.
When I first started learning cypher I was always forgetting which order to put the different key words and what the syntax was for selecting your starting node.
After a while you do get the hang of it though and it starts to feel like any other programming language.
If we didn’t have the node ids of our source and destination nodes but we had two people’s names which had been stored in a ‘people’ Lucene index then we could just as easily find the path between them like this:1.START source=node:people(name="Mark Needham"), destination=node:people(name="Cameron Swords")
2.MATCH p = allShortestPaths(source-[r:colleagues*..3]->destination)
3.RETURN NODES(p)复制代码I use cypher for pretty much everything I do when reading from the graph and since version 1.8 M01 it’s been possible to construct queries which mutate the graph as well.

回复

使用道具 举报

千问 | 2014-2-19 11:55:14 | 显示全部楼层
over.
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

主题

0

回帖

4882万

积分

论坛元老

Rank: 8Rank: 8

积分
48824836
热门排行